带有spring restcontroller的跨域ajax请求问题

时间:2015-07-23 04:30:46

标签: jquery ajax spring spring-mvc

我遇到了使用ajax的跨域请求问题。

以下是我的春季控制器代码:

@RestController
@RequestMapping(value = "/help")
public class MYController {

        @Autowired
        private MyService myService;

        private static final int SUCCESS = 1;
        private static final int FAIL    = 0;

        @RequestMapping(value = "save", method = RequestMethod.POST,produces={"application/json"})
        public int save(@RequestBody Item item,HttpServletRequest request,HttpServletResponse response) {

                response.addHeader("Access-Control-Allow-Origin","*");  
                response.addHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, OPTIONS");  
                response.addHeader("Access-Control-Allow-Headers","Content-Type, Content-Range, Content-Disposition, Content-Description");  

                try {
                        myService.save(item);
                        return SUCCESS;
                } catch (Exception ex) {
                        ex.printStackTrace();
                        return FAIL; 
                }
        }  
}

上面的代码是我的休息服务的一部分,它在其他tomcat上运行。

以下是我的脚本代码,这是我的客户端代码。

$.ajax({
               type: "POST",
               url:"http://10.10.13.215:9092/helpProject/help/save",
               crossDomain: true,
               dataType: "JSON",
               data:JSON.stringify(item), //item is my pojo here
               headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
                   success: function(msg) {
                         alert(msg);
            },
             error: function (e) { 
                   alert("errorrrrrr");
             }
            });

我在浏览器的控制台中收到以下错误:

XMLHttpRequest cannot load http://10.10.13.215:9092/helpProject/help/save",
     No 'Access-Control-Allow-Origin' header is present on the requested resource. 
     Origin 'http://localhost:8082' is therefore not allowed access.

请帮忙解决..谢谢

1 个答案:

答案 0 :(得分:2)

尝试添加此过滤器。

@Component
public class CorsFilter implements Filter {


@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub

}


@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods",
            "POST, GET, OPTIONS, DELETE");
    res.setHeader("Access-Control-Max-Age", "3600");
    res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    chain.doFilter(request, res);
}


@Override
public void destroy() {
    // TODO Auto-generated method stub

}

}