web整合spring注意事项

1.web.xml

<!-- Shiro配置 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>	

DelegatingFilterProxy 作用是自动到 spring 容器查找名字为 shiroFilter(filter-name)的 bean
并把所有 Filter 的操作委托给它。然后将 ShiroFilter 配置到 spring 容器即可:

spring-context-shiro.xml

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 
<property name="securityManager" ref="securityManager"/> 
<!—忽略其他,详见与 Spring 集成部分 --> 
</bean> 

最后,web.xml使用 org.springframework.web.context.ContextLoaderListener 加载这个 spring配置文件即可

<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

2.springmvc.xml  配置shiro注解

    <!--启用shiro注解 -->
    <bean
        class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
        depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>
    <bean
        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager" />
    </bean>

可以通过类似@RequiresRoles("admin") 仅限角色/权限验证,

失败将抛出UnauthorizedException异常,使用Spring的ExceptionHandler(DefaultExceptionHandler)来进行拦截处理:

定义了异常处理类
 

package com.cxy.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class DefaultExceptionHandler {
	 @ExceptionHandler({UnauthorizedException.class})
	    @ResponseStatus(HttpStatus.UNAUTHORIZED)
	    public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
	        ModelAndView mv = new ModelAndView();
	        mv.addObject("ex", e);
	        mv.setViewName("unauthorized");
	        return mv;
}
}

前端使用 ${ex.message},可以得到详细的信息

权限注解

@RequiresAuthentication  表示当前 Subject 已经通过 login 进行了身份验证;即 Subject. isAuthenticated()返回 true。

@RequiresUser  表示当前 Subject 已经身份验证或者通过记住我登录的

@RequiresGuest  表示当前 Subject 没有身份验证或通过记住我登录过,即是游客身份

@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)  表示当前 Subject需要角色admin 和user

@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR)   表示当前 Subject需要角色admin或user

猜你喜欢

转载自blog.csdn.net/qq_38930240/article/details/86680782