在上一篇中我们遗留了一个问题就是当没有权限时页面跳转的问题。
首先搭建一个jsp的环境
pom文件:
4.0.0
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
com.shiro
demo
0.0.1-SNAPSHOT
shiro
war
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.apache.shiro
shiro-spring
1.4.0
io.jsonwebtoken
jjwt
0.9.1
org.apache.tomcat.embed
tomcat-embed-jasper
javax.servlet
javax.servlet-api
javax.servlet
jstl
org.springframework.boot
spring-boot-maven-plugin
applocation.yml文件:
server:
port: 8202
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
访问jsp的Controller:
package com.shiro.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "jsp")
public class JspController {
@RequestMapping(value = "test")
public String aaa(){
System.out.println("111111111111111111111");
return "index";
}
}
项目结构:
首先测试一下http://localhost:8202/jsp/test能不能正常访问。如果能进行下面的步骤。
修改ShiroConfig类的shiroFilter方法:
我们新增了
shiroFilterFactoryBean.setUnauthorizedUrl("/jsp/test");
filterChainDefinitionMap.put("/test/admin","perms[user:view]");
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(securityManager);
//shiroFilterFactoryBean.setLoginUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/jsp/test");
//自定义过滤器
Map filterMap = new LinkedHashMap<>();
filterMap.put("filter",new ShiroFilter());
shiroFilterFactoryBean.setFilters(filterMap);
//权限控制map
Map filterChainDefinitionMap = new LinkedHashMap<>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/static/**", "anon");
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/test/login","anon");
filterChainDefinitionMap.put("/test/admin","perms[user:view]");
//filterChainDefinitionMap.put("/test","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
同时将admin方法上面的@RequiresPermissions({"user:delete","user:update"})注释掉。
需要注意的是测试的时候一定要先执行login方法。
当前用户拥有的权限是:user:delete。所以访问时没有权限。即跳转到/jsp/test路径
继续修改代码:
将filterChainDefinitionMap.put("/test/admin","perms[user:view]");注释掉。同时在admin方法中添加@RequiresPermissions({"user:delete","user:update"})
会发现并没有跳转到/jsp/test路径去。具体原因访问https://blog.csdn.net/bicheng4769/article/details/86680955
新增一个MyControllerAdvice类来处理全局异常。
package com.shiro.MyException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class MyControllerAdvice {
@ExceptionHandler(value = UnauthorizedException.class)
public String aa(){
return "index";
}
}
我们再次访问test/admin方法。会发现能够跳转到/jsp/test路径去了。