第一步编写自定义异常:
public class WebBusinessCommonException extends RuntimeException{
private String code;
private String message;
public WebBusinessCommonException(String code,String message) {
super(message);
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
第二步:编写全局控制异常类,统一抛出异常,编写统一抛出的jsp
public class WebCommonExceptionResolver implements HandlerExceptionResolver {
private Logger log = LoggerFactory.getLogger(WebCommonExceptionResolver.class);
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object object, Exception exception) {
log.info(exception.getMessage());
if (exception instanceof WebBusinessCommonException) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("errorMsg", exception.getMessage());
//我们自定义的异常都统一跳转到error.jsp页面
return new ModelAndView("/error/commonerror", map);
}
//其他异常我们都统一跳转到error.jsp页面
return "";
}
}
第三步:
spring-mvc.xml配置
<bean id="handlerExceptionResolver" class="cn.xxx.xxxx.WebCommonExceptionResolver"/>
第四步:编写自定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PermissionAnnotation {
public boolean value() default false;
}
第五步:编写aop工具类
@Component
@Aspect
public class PermissionAopUtils {
private Logger log = LoggerFactory.getLogger(PermissionAopUtils.class);
ThreadLocal<Long> startTime = new ThreadLocal<>();
/**
* 定义切面
* - 此处代表cn.xxx.xxxx.xxx.web..web.controller包下的所有接口都会被统计
* && @annotation(permissionAnnotation)
*/
@Pointcut("execution(* cn.xxx.xxxx.xxx.web.controller..*.*(..))")
public void pointCut(){
}
/**
* 在接口原有的方法执行前,将会首先执行此处的代码
*/
@Before("pointCut() && @annotation(permissionAnnotation)")
public void doBefore(JoinPoint joinPoint,PermissionAnnotation permissionAnnotation) {
startTime.set(System.currentTimeMillis());
//获取传入目标方法的参数
/* Object[] args = joinPoint.getArgs();
log.info("类名:{}", joinPoint.getSignature().getDeclaringType().getSimpleName());
log.info("方法名:{}", joinPoint.getSignature().getName() );*/
log.info("当前权限:"+permissionAnnotation.value());
if(permissionAnnotation.value()){
throw new WebBusinessCommonException("000001","无权限查看");
}
}
}
第六步:要用的controller或service中要校验权限的加此注解
@RequestMapping(value = {"toadd"})
@PermissionAnnotation(true)
public String toAdd(Model model){
return "xxxx/xxxx_list";
}
这样访问toAdd方法就会校验权限跳到统一界面