shiro注解,初始化资源和权限,会话管理

 有具体问题的可以参考之前的关于shiro的博文,关于shiro的博文均是一次工程的内容 

注解:

 

新建一个类:
此时需要有admin的权限才可以执行下面的代码
public class ShiroService {
     
     @RequiresRoles({"admin"})
     public void testMethod(){
           System.out.println("test。。。。。");
     }
}

 把新建的类注入到spring容器中 

 <bean  class="com.MrChengs.shiro.service.ShiroService"></bean>

ShiroHandler .java中加入

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {
     
     
     @Autowired
     private ShiroService shiroService;
     
     @RequestMapping("/testMethod")
     public String testMethod(){
           shiroService.testMethod();
           return "redirect:/list.jsp";
     }
     ....
}     

 list.jsp中加入测试超链接

  <a href="shiro/testMethod">Test Method</a>
 
此时我们登陆admin可以成功测试
 
当我们登陆user再点击测试的时候
UnauthorizedException

 初始化资源和权限

 点击看源码可知

 

其配置的文件的内容最终被封装成一个map

新建一个初始化文件的类:
在map的方法体里面可以写我们需要在数据库中查询等代码
LinkedHashMap一定是这个
package com.MrChengs.shiro.Factory;
import java.util.LinkedHashMap;
public class FilterChainDefinitionMapperBUilder {
     public LinkedHashMap<String, String>  builderFilterChainDefinitionMap(){
           LinkedHashMap<String, String> map = new  LinkedHashMap<String, String>();
           map.put("/login.jsp", "anon");
           map.put("/shiro/login", "anon");
           map.put("/shiro/logout", "logout");
           map.put("/user.jsp", "roles[user]");
           map.put("/admin.jsp", "roles[admin]");
           map.put("/**", "authc");
           return map;
     }
}
在application中:
把注释的地方替换成红色标准的地方
  <!--
        <property name="filterChainDefinitions">
            <value>
                /login.jsp = anon
                  /shiro/login = anon
                  /shiro/logout = logout
                  /user.jsp = roles[user]
                  /admin.jsp = roles[admin]
                # everything else requires authentication:
                /** = authc
            </value>
        </property>
        -->
        <property name="filterChainDefinitionMap"  ref="filterIniDef"></property>
    <!-- 配置一个bean,实际上是一个map,实例通过工厂模式的方法 -->
    <bean id="filterIniDef"  factory-bean="filterChainDefinitionMapperBUilder"
    factory-method="builderFilterChainDefinitionMap"></bean>
    
    <bean id="filterChainDefinitionMapperBUilder"  class="com.MrChengs.shiro.Factory.FilterChainDefinitionMapperBUilder"></bean>
    

 其余不变测试时没有任何问题的!!!

 会话管理

 

 

测试如下

 

猜你喜欢

转载自www.cnblogs.com/Mrchengs/p/9997494.html