此文是在已经配置好shiro的前提下。
一、编程方式:通过java代码
@RequestMapping(value="/main",method=RequestMethod.GET)
public String loginForm(HttpServletResponse response,HttpServletRequest request,Model model){
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.hasRole("admin")) {
logger.info("-----------啊啊啊啊--admin---------");
}
if (currentUser.hasRole("user")) {
logger.info("-----------user---------");
}
return "sys/main";
}
二、JSP标签:
<shiro:authenticated> <p>登录之后</p></shiro:authenticated>
<shiro:notAuthenticated> 未登录</shiro:notAuthenticated><input type="button" name="dianji" id="dianji"onclick="login()"/>
<shiro:hasRole name="manager">manager角色</shiro:hasRole>
<shiro:hasRole name="admin">我admin角色</shiro:hasRole>
<shiro:hasRole name="admins">我有admins角色 </shiro:hasRole>
<shiro:lacksRole name="user">没有user角色</shiro:lacksRole>
<shiro:hasPermission name="manager"><p>你有权限看到此处!</p></shiro:hasPermission>
三、通过注解方式:放在controller 方法头上(但是之前放在service可行,后来不行了,不知道为什么)
//shiro权限校验
//@RequiresRoles({"xcxcxc"})//角色校验
@RequiresPermissions({"xcxcxc"})//权限校验
@RequestMapping("/queryUser")
@ResponseBody
但是该方法直接抛出异常。
不会调用这个方法,shiroFilterFactoryBean.setUnauthorizedUrl("/sys/403");//无权限时候跳转。
解决方式:
1.自定义一个类,当出现异常时候调用。然后执行我们需要的方法
1.1先新建一个类:MyExceptionResolver.java
/**
* 用于解决 无权限时候 shiroFilterFactoryBean.setUnauthorizedUrl("/shiro/403"); 的跳转
* create_by krystal on 2018/11/15/015.
*/
public class MyExceptionResolver implements HandlerExceptionResolver{
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// TODO Auto-generated method stub
System.out.println("==============异常开始=============");
//如果是shiro无权操作,因为shiro 在操作auno等一部分不进行转发至无权限url
if(ex instanceof UnauthorizedException){
ModelAndView mv = new ModelAndView("/sys/403");
return mv;
}
ex.printStackTrace();
ModelAndView mv = new ModelAndView("/sys/403");
mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
return mv;
}
}
1.2springboot在启动类里加上:
//解决无权限不跳转,直接报错问题部分
@Bean
public HandlerExceptionResolver solver() {
HandlerExceptionResolver handlerExceptionResolver = new MyExceptionResolver();
return handlerExceptionResolver;
}
执行该方法:
debugger时候会进这边。
2.直接在配置权限的时候
filterChainDefinitionMap.put("/sysUser/queryUser", "authc,perms[xcxcxc]");在执行该方法时候会校验是否有权限“xcxcxc”
若无会直接跳转到shiroFilterFactoryBean.setUnauthorizedUrl("/sys/403");//无权限时候跳转这里