引文:shiro自带有多种过滤器,但是在一些场景中,需要登录页面有多种展现形式,通常需要用一些字段参数来控制,这个时候shiro的过滤不能满足需求,需要注入自定过滤器来满足需求
1.自定义过滤器,实现
public class LoginFilter extends AuthenticationFilter {
/** 用户没登录时操作 */
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
// 获取登陆前请求路径
HttpServletRequest request = (HttpServletRequest) servletRequest;
String uri = request.getRequestURI();
// 记录请求路径,用于登陆后跳转
servletRequest.setAttribute("previousUri", uri);
// 自定义规则,根据不同规则转发
if (uri.equals("/")) {
servletRequest.getRequestDispatcher("/loginPage?type=0").forward(servletRequest, servletResponse);
} else {
servletRequest.getRequestDispatcher("/loginPage?type=1").forward(servletRequest, servletResponse);
}
// 请求不再往下传递
return false;
}
}
2.在ShiroConfig配置类中注入自定义过滤器,并设置映射路径
/** Filter工厂,设置对应的过滤条件和跳转条件 */
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 放入自定义过滤器,命名为“loginFilter”
HashMap<String, Filter> filterHashMap = new HashMap<>();
filterHashMap.put("loginFilter", new LoginFilter());
shiroFilterFactoryBean.setFilters(filterHashMap);
// 设置各拦截器映射路径
Map<String, String> map = new HashMap<>();
// 不拦截
map.put("/logout", "anon");
map.put("/loginPage", "anon");
map.put("/login", "anon");
map.put("/bigscreen/upload/*", "anon");
// 拦截
map.put("/", "loginFilter");
map.put("/bigscreen/**", "loginFilter");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
尝试成功