这篇文章主要介绍Java拦截器和切面怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
拦截器的使用:每次接收到某个请求之前,都会调用此拦截器中的方法,其中preHandle方法如果return true,表示继续调用对应的controller,如果return false,
public class CheckLoginInterceptor implements HandlerInterceptor { private Logger logger = Logger.getLogger(CheckLoginInterceptor.class); private static String TOKEN_VALID_MSG ; static { TOKEN_VALID_MSG=JsonUtil.writeObject2JSON(new AMSResultVO(CodeNum.TOKEN_VALID, CodeMessage.TOKEN_VALID)); } public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //request.getMethod获取请求是get,post等 if ("OPTIONS".equals(request.getMethod())) { // 指定允许其他域名访问 response.setHeader("Access-Control-Allow-Origin", "*"); // 响应类型 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // 响应头设置 response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header"); response.setStatus(204); return true; } // 获取从header中得到的数据 String userName = request.getHeader(CommonConsts.PARAM_USER_NAME); String userToken = request.getHeader(CommonConsts.PARAM_USER_TOKEN); Boolean result = true; String method = request.getRequestURI(); if(method.equals("/ams/fileUpload")) { return true; } if(StringUtil.isEmpty(userName) || StringUtil.isEmpty(userToken)) { result = false; } else { result = TokenUtil.validToken(userName, userToken); } // token校验失败 if(!result) { response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(TOKEN_VALID_MSG); response.getWriter().flush(); response.getWriter().close(); } return result; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
切面的使用:
//坏绕通知:需要携带ProceedingJoinPoint类型的参数 //环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法 //且环绕通知必须有返回值,返回值即目标方法的返回值。 @Around("execution(* com.sowell.controller.*Controller.*(..))") public Object aroundMethod(ProceedingJoinPoint pjd) { Object result = null; String methodName = pjd.getSignature().getName(); Object args = Arrays.asList(pjd.getArgs()); //执行目标方法 try { logger.info("request channels begin, param{pageNum:" + methodName + ", pageSize:" + args); //前置通知,表示在此之前的代码会在调用controller之前调用 result = pjd.proceed(); recordOprationLog(result, methodName, result); //后置通知 logger.info("Arround:The method "+ methodName+" ends"); } catch (Throwable e) { e.printStackTrace(); //异常通知 logger.error("Arround:The method "+ methodName+"occurs exception:"+e); //throw new RuntimeException(e); //不抛出异常的话,异常就被上面抓住,执行下去,返回result,result值为null,转换为int } //返回通知 logger.info("Arround:The method "+ methodName+" ends with the Result "+ result); return result; }
以上是“Java拦截器和切面怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。