正确代码:
@Configuration
public class ShiroConfig {
@Bean
public MyRealm createMyRealm(){
MyRealm myRealm = new MyRealm();
return myRealm;
}
@Bean
public SecurityManager createSecurityManager(MyRealm myRealm){
SecurityManager securityManager = new SecurityManager();
securityManager.setRealm(myRealm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean createShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
// 设置拦截的规则
HashMap<String, String> rule = new HashMap<>();
// 设置登录页面
shiroFilterFactoryBean.setLoginUrl("/login.html");
// 设置未授权的页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized.html");
// 拦截全部资源
rule.put("/**","authc");
// 放行登录页面
rule.put("/login.html","anon");
rule.put("/unauthorized.html","anon");
// 设置拦截规则
shiroFilterFactoryBean.setFilterChainDefinitionMap(rule);
return shiroFilterFactoryBean;
}
}
常见错误:
一、@Configuration注解未写导致容器无法注入
二、使用@Autowired的方式注入myRealm导致多线程使用时数据混乱,因为@Autowired注入的方式为单例模式
三、SecurityManager 类导入错误,到成java.lang包下面的SecurityManager,正确的应该是Shiro包下的SecurityManager