cors解决跨越问题

转载于http://www.cnblogs.com/jiangwz/p/8142740.html

Cross-Origin Resource Sharing(CORS)跨来源资源共享是一份浏览器技术的规范,提供了 Web 服务从不同域传来沙盒脚本的方法,以避开浏览器的同源策略,是 JSONP 模式的现代版。与 JSONP 不同,CORS 除了 GET 要求方法以外也支持其他的 HTTP 要求。用 CORS 可以让网页设计师用一般的 XMLHttpRequest,这种方式的错误处理比 JSONP 要来的好。另一方面,JSONP 可以在不支持 CORS 的老旧浏览器上运作。现代的浏览器都支持 CORS。

 

配置过滤器

public class SimpleCORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("SimpleCORSFilter启动!!!===========");
    }

    @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, response);
    }

    @Override
    public void destroy() {
        System.out.println("SimpleCORSFilter结束!!!===========");
    }

}

配置web.xml文件:

 <!-- cors解决跨域访问问题 -->
    <filter>
        <filter-name>cors</filter-name>
        <filter-class>com.wazn.learn.util.SimpleCORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

调用的方法

 @RequestMapping("select")
    @ResponseBody
    public JSONObject select(int page , int limit , String title){
        JSONObject jo = new JSONObject();
        Map<String,Object> map = newsService.select(page,limit,title);
        jo.put("code",0);
        jo.put("msg", true);
        jo.put("data", map.get("data"));
        jo.put("count", map.get("count"));
        return jo;
    }

前台接受

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
    </head>
    <body>
        <h1>ajax测试接口</h1>
    </body>
    <script type="text/javascript">
        $(function() {
            $.ajax({
                type:"post",
                url:"http://192.168.1.113/basepro/knowledge/news/select",
                data:{
                    page:1,
                    limit:1000
                },
                dataType:"json",//返回的
                success:function(data) {
                    alert(data.msg);       
                },
                error:function(msg) {
                    console.log(msg);
                }
            });
        });
    </script>
</html>

返回图片

posted @ 2018-01-17 09:41  *眉间缘*  阅读(285)  评论(0编辑  收藏  举报