不要在该奋斗的年纪选择了安逸;|

黎华扬

园龄:8年1个月粉丝:4关注:3

跨域AJAX请求

在处理跨域AJAX请求有许多方法。我这里用的是 CORS,

CORSFilter

CORSFilter是Apache官方提供一个支持CORS跨域的过滤器:

详细说明: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

在maven配置文件中导入依赖

<!--CORS-->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.6</version>
</dependency>    

在web.xml添加过滤器

复制代码
<filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>http://127.0.0.1:8020</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedMethods</param-name>
            <param-value>POST,GET,OPTIONS,DELETE,PUT</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Content-Type,Accept,Origin,XRequestedWith,ContentType,LastModified</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposedHeaders</param-name>
            <param-value>SetCookie</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportsCredentials</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
复制代码

 

客户端

复制代码
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>跨域AJAX请求</title>
    </head>

    <body>
        <h2>跨域AJAX请求</h2>
        <button type="button" id="btnAjax">ajax请求</button>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript">
            $("#btnAjax").click(function() {
                $.get("http://localhost:8080/mvc02/users", "", function(data) {
                    console.log(JSON.stringify(data));
                }, "json");
            });
        </script>
    </body>

</html>
复制代码

 

服务器(本人用的是Spring MVC):

复制代码
@RestController
@RequestMapping(path="/users")
public class UsersController {
    @Resource
    EmpService empService;

    /*查询所有*/
    @RequestMapping(path = "",method = RequestMethod.GET)
    public List seletUser(){
        return empService.findEmpList();
    }
}
复制代码

结果:

 

 Spring MVC4.2 及以上增加了对CORS的支持

一个应用可能会有多个 CORS 配置,并且可以设置每个 CORS 配置针对一个接口或一系列接口或者对所有接口生效 

如果想要对某一接口配置 CORS,可以在方法上添加 CrossOrigin 注解:

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
    return "{\"project\":\"just a test\"}";
}

 

如果想对一系列接口添加 CORS 配置,可以在上添加注解,对该类声明所有接口都有效

@CrossOrigin(origins = {"http://localhost:8080", "null"})
@RestController
public class HomeController{
}

 

全局配置,则需要添加一个配置类

复制代码
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:9000", "null")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}
复制代码

 

也可以通过添加 Filter 的方式,配置 CORS 规则,并手动指定对哪些接口有效

复制代码
@Bean

public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);    config.addAllowedOrigin("http://localhost:9000");
    config.addAllowedOrigin("null");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
    FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}
复制代码

也可以修改配置文件

<mvc:cors>
        <mvc:mapping path="/**"
                     allowed-origins="http://127.0.0.1:8020"
                     allowed-methods="POST,GET, OPTIONS,DELETE,PUT"
                     allowed-headers="Content-Type,ContentType,Access-Control-Allow-Headers, Authorization, X-Requested-With"
                     allow-credentials="true"/>
    </mvc:cors>

 

资料来源于 http://www.cnblogs.com/best/p/6196202.html#_lab2_2_3

本文作者:黎华扬

本文链接:https://www.cnblogs.com/galenblog/p/8034681.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   黎华扬  阅读(283)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起