时间:2020-10-31 17:21:37 | 栏目: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拦截器和切面的使用实例详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!