拦截器创建
1、创建拦截器
@Component public class RequestInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(request.getMethod().equals("OPTIONS")){ return true; } System.out.println("it is preHandle"); String accessToken= request.getHeader("accessToken"); System.out.println("mehtod:"+request.getMethod()+"; accessToken = " + accessToken); boolean resultFlag=true; if(resultFlag){ Result result=new Result(); result.msg="22222"; result.code="001"; setResult(request,response,result); return false; } return true; } /** * 验签失败返回结果信息 * * @param request * @param response * @param result */ private void setResult(HttpServletRequest request, HttpServletResponse response, Result result) { response.setContentType("application/json; charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.addHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Access-Control-Allow-Headers", "accessToken,traceID,productCode,productVersion,appKeySign,clientIP"); PrintWriter out = null; try { out = response.getWriter(); out.append(JSON.toJSON(result).toString()); } catch (IOException e) { // logger.error("ValidateAPPKeyInterceptor setResult", e); } finally { if (out!=null) { out.close(); } } } }
2、设置拦截器放行地址和启用拦截器
@Configuration public class MywebConfig implements WebMvcConfigurer { @Resource RequestInterceptor requestInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(requestInterceptor) .addPathPatterns("/**"); } }
3、拦截器中不通过时返回结果
/** * 验签失败返回结果信息 * * @param request * @param response * @param result */ private void setResult(HttpServletRequest request, HttpServletResponse response, Result result) { response.setContentType("application/json; charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.addHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Access-Control-Allow-Headers", "accessToken,traceID,productCode,productVersion,appKeySign,clientIP"); PrintWriter out = null; try { out = response.getWriter(); out.append(JSON.toJSON(result).toString()); } catch (IOException e) { // logger.error("ValidateAPPKeyInterceptor setResult", e); } finally { if (out!=null) { out.close(); } } }