UnauthorizedException的处理
在开发过程中,当一个用户进行删除操作或者其他操作的时候,需要授权给用户之后才可以进行,其中授权的过程可以在一个请求的方法上边加上@RequiresPermissions(“edit”)注解
但是在没有授权的用户操作授权的过程中,如果没有授予edit权限的时候,会抛出异常UnauthorizedException,这个时候就需要自定义一个异常解析类,来处理这个异常,具体如下:
package com.wbs.wbsbs.exception;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class MyUnauthorizedException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
System.out.println("==============MyUnauthorizedException=============");
//如果是shiro无权操作,因为shiro 在操作auno等一部分不进行转发至无权限url
if(e instanceof UnauthorizedException){
ModelAndView mv = new ModelAndView("/unauthorized/index");
return mv;
}
e.printStackTrace();
System.out.println("==============其他异常=============");
ModelAndView mv = new ModelAndView("/error/index");
mv.addObject("exception", e.toString().replaceAll("\n", "<br/>"));
return mv;
}
}
这样的话,授权过程中抛出UnauthorizedException异常的时候,可以通过我们制定的ModelAndView跳转到具体的页面,提示用户没有该权限