解释 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //支持跨域请求 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization"); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // 跨域时会首先发送一个OPTIONS请求,这里我们给OPTIONS请求直接返回正常状态 if (request.getMethod().equals(RequestMethod.OPTIONS.name())) { response.setStatus(HttpStatus.OK.value()); return false; } IgnoreAuth annotation; if (handler instanceof HandlerMethod) { annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class); } else { return true; } //从header中获取token String token = request.getHeader(LOGIN_TOKEN_KEY); /** * 不需要验证权限的方法直接放过 */ if(annotation!=null) { return true; } TokenEntity tokenEntity = null; if(StringUtils.isNotBlank(token)) { tokenEntity = tokenService.getTokenEntity(token); } if(tokenEntity != null) { request.getSession().setAttribute("userId", tokenEntity.getUserid()); request.getSession().setAttribute("role", tokenEntity.getRole()); request.getSession().setAttribute("tableName", tokenEntity.getTablename()); request.getSession().setAttribute("username", tokenEntity.getUsername()); return true; } PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(JSONObject.toJSONString(R.error(401, "请先登录"))); } finally { if(writer != null){ writer.close(); } } // throw new EIException("请先登录", 401); return false; }
时间: 2024-02-15 21:29:06 浏览: 191
利用SpringMVC过滤器解决vue跨域请求的问题
5星 · 资源好评率100%
这段代码是一个Java的拦截器,用于对请求进行预处理。在这个方法中,首先设置了支持跨域请求的相关参数,然后判断是否为OPTIONS请求,如果是则直接返回正常状态。接下来判断是否有IgnoreAuth注解,如果有则直接放过,否则从请求头中获取Token,并通过TokenService验证Token的有效性。如果Token有效,则将相关信息存入Session中,否则返回401错误提示。最后,返回true或者false表示是否允许请求继续处理。
阅读全文