Java server-side cors cross-domain access restful interface

What is the cross-origin request problem?

The cause of this problem is that modern browsers block cross-domain ajax requests by default for security reasons. This is a must-have feature in modern browsers, but it often brings inconvenience to development.

However, the need for cross-domain has always been there. In order to cross-domain, hard-working and brave programmers have come up with many methods, such as jsonP, proxy files and so on. However, these practices increase a lot of unnecessary maintenance costs, and there are many limitations in application scenarios. For example, jsonP is not XHR, so jsonP can only use GET to pass parameters.

Nowadays, mobile applications are booming. Thanks to HTML5, Mobile Web and even Hybird App are gradually becoming popular. On the web pages of the local file system, there is also a need to obtain external data, and these requirements must also be cross-domain. of. At the same time, HTML5 also brings a new feature called "Cross-Origin Resource Sharing" to empower developers to decide whether resources are allowed to be accessed across domains.

How to solve?

CORS, CrossOrigin Resources Sharing, is a feature of HTML5 that defines a way for browsers and servers to interact to determine whether to allow cross-origin requests.

Add a special Header[Access-Control-Allow-Origin] to the server to inform the client of cross-domain restrictions. If the browser supports CORS, if the Origin is judged to pass, XHR will be allowed to request, and there is no need to use it again. jsonP or proxy file.

Use this Header to return the origin domain that is allowed to request cross-domain requests. For example, the website duelist.cn sets the following Header

Access-Control-Allow-Origin: http://smdcn.net

After this setting, the ajax request to duelist.cn through the page under http://smdcn.net will be allowed, while other websites will still be blocked for duelist.cn. In this way, the website owner can do this by himself limit.

Of course, if you don't want to restrict the origin, you can allow any site to make cross-domain requests to the resource through

Access-Control-Allow-Origin: * Solution under SpringMVC: define SimpleCORSFilter import java.io.IOException; import javax.servlet. Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework .stereotype.Component; @Component public class SimpleCORSFilter implements Filter {

















  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");//所有请求     
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));// cookie共享用这个配置
   response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,X-E4M-With,userId,token"); 
        response.setHeader("Access-Control-Allow-Credentials", "true");//cookie 共享
        response.setHeader("XDomainRequestAllowed","1"); 
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}

web.xml:

<filter>
  <filter-name>cors</filter-name>
  <filter-class>com.app.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

angularjs端代码:

     $http({
  method:"post",
  url: "http://localhost:8080/eifs/usr/login.json",
  data: {para1:"para1",para2:"para2"},
  headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
  }
}).success(function (data) {
}).error(function (data) {
});
$http.get('http://localhost:8080/eifs/usr/login.json', {params:{para1:"para1",para2:"para2"},timeout: 10000})
.success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
/ /cookie 共享时 配置 withCredentials :true
$http.get("http://127.0.0.1:8080/xxx/syslogin/login?account=%E5%B0%8F%E7%81%B0&password=123456",{ withCredentials: true });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326689299&siteId=291194637