@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { System.out.println("-----------------------进入拦截器-------------------------"); //每次都会先发一个不带参数的OPTIONS请求,若此请求失败则不会发起正式请求,所以要过滤掉OPTIONS请求 if (HttpMethod.OPTIONS.toString().equals(request.getmethod())) { System.out.println("OPTIONS请求,放行"); return true; } try { String token=request.getHeader("Authorization"); //如果验证token失败,并且方法注明了Authorization,返回401错误 if (token == null) { //设置response状态 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); //返回的数据 JSONObject res = new JSONObject(); res.put("status","-1"); res.put("msg","need login"); PrintWriter out = null ; out = response.getWriter(); out.write(res.toString()); out.flush(); out.close(); return false; } }catch (Exception e){ return false; } return true; }