官方推荐方式: http://spring.io/blog/2015/06/08/cors-support-in-spring-framework 方式1: $.ajax({ //前台:常规写法。注意:如果用注解dataType别写成了JSONP 要写成JSON 两都有区别。一个是协议一个是数据格式(个人理解) url:'http://localhost:8082/cors/corsTest.do', data:{}, dataType:'json', type:'post', success:function(data){ alert(data.abc); } }) // 后台代码 。。。 添加注解即可。CrossOrigin(这里可能配置多个地址。不配置默认全部 可以配置到controller上面。也可以配置方法上。都配置他会自动合并) @SuppressWarnings("unchecked") @RequestMapping(value="/corsTest",method = RequestMethod.POST) @ResponseBody @CrossOrigin public Object corsTest(){ Map map = new HashMap(); map.put("abc", 123); return map; } 方式2: $.ajax({ //不采用注解方法,手动拼一个callback字符串。 url:'http://localhost:8082/cors/corsTest1.do', data:{}, async:false, dataType:'jsonp', jsonpCallback:"callback", type:'post', success:function(data){ alert(data.abc); } }) 后台代码: @RequestMapping(value="/corsTest1") @ResponseBody public Object corsTest1(){ Map map = new HashMap(); map.put("abc", 456); return "callback("+JSON.toJSONString(map)+")"; } 方式3: 即不采用注解也不采用手动拼接字符串的方式 。就是用拦截器方式; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // 跨域 String origin = httpRequest.getHeader("Origin"); if (origin == null) { httpResponse.addHeader("Access-Control-Allow-Origin", "*"); } else { httpResponse.addHeader("Access-Control-Allow-Origin", origin); } httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, Content-Type, Accept,X-Cookie"); httpResponse.addHeader("Access-Control-Allow-Credentials", "true"); httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE"); if ( httpRequest.getMethod().equals("OPTIONS") ) { httpResponse.setStatus(HttpServletResponse.SC_OK); return; } chain.doFilter(request, response); } catch (Exception e) { logger.error("Exception in crossFilter", e); throw e; } } 然后在web.xml配置一下就行了。 <filter> <filter-name>crossDemoFilter</filter-name> <filter-class>com.shanreal.filter.crossFilter</filter-class> </filter> <filter-mapping> <filter-name>crossDemoFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 还有一种就是通过nginx配置。学习中