public class TestFilter implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //返回true 则可放行 false不放行 String type = request.getMethod(); //添加ajax跨域支持 if (type.toUpperCase().equals("OPTIONS") == true) { response.setCharacterEncoding("utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "content-type, accept"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setStatus(200); response.setContentType("application/json;charset=utf-8"); Map<String, Object> resObject = new HashMap<>(); resObject.put("状态", "成功"); resObject.put("消息", "接口是通的"); String data = JsonUtil.toJson(resObject);//这里就是把对象转为json OutputStream outputStream = response.getOutputStream(); byte[] dataByteArr = data.getBytes("UTF-8"); outputStream.write(dataByteArr); return false; } }
后端加上这个处理就行了。
前端ajax请求记得设置contentType:"application/json;charset=utf-8"就行了