基于【shiro集成spring】项目改造

引入相关依赖环境

 <!--AOP的jar包-->
 <dependency>
     <groupId>org.aspectj</groupId>
     <artifactId>aspectjweaver</artifactId>
     <version>1.9.4</version>
 </dependency>

构建shiro 注解配置

在SpringMVC的配置文件中增加以下配置

<!--shiro注解配置-->
<!--调用工程中的组件-->
<bean id="lifecycleBeanPostProcessor"
      class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>

<!--如果发现此配置,会在当前工厂中多创建一个后处理器-->
<aop:config></aop:config>

<!--提供shiro注解组件-->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"></property>
</bean>
     

注解的使用

可以注解在controller类上或者方法上,可以叠加使用

@RequiresGuest  #游客身份

@RequiresAuthentication #必须登录

@RequiresRoles(value = {"admin","manager"},logical = Logical.OR) #必须是admin或者mannager的角色

@RequiresPermissions("user:query") #必须有user:query的权限

未登录或者无权限跳转页面

com\shiro\resolver\MyExceptionResolver.java

package com.shiro.resolver;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        System.out.println(e.getClass());
        ModelAndView mv = new ModelAndView();
        if(e instanceof IncorrectCredentialsException || 
                e instanceof UnknownAccountException ||
                e instanceof UnauthenticatedException){
            //跳转到登录界面
            mv.setViewName("redirect:/user/login");
        }
        return mv;
    }
}

注册自定义异常类

resources\springmvc-servlet.xml

<bean class="com.shiro.resolver.MyExceptionResolver"></bean>

删除shiro配置文件的相关配置

shiroFilter bean标签只保留以下内容 其他的内容删掉
resources\spring-shiro.xml

<!--shiroFilter 角色权限校验-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <!--注入核心对象:securityManager-->
    <property name="securityManager" ref="securityManager" />
</bean>

登出

@RequestMapping("/logout")
public String logout(){
    SecurityUtils.getSubject().logout();
    return "login";
}

版权声明:本文为applesnt原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/applesnt/p/12721524.html