SpringMvc + AngularJS implements cross-origin scheme through CORS, springmvccors

Source: Internet
Author: User

SpringMvc + AngularJS implements cross-origin scheme through CORS, springmvccors

What is a cross-origin request?

The cause of this problem is that modern browsers block cross-origin ajax requests based on security reasons by default. This is a necessary function in modern browsers, but it is often inconvenient for development.

However, cross-domain requests have always been raised. For cross-domain requests, brave programmers have come up with many methods, such as jsonP and proxy files. However, these practices increase unnecessary maintenance costs and impose many restrictions on application scenarios. For example, jsonP is not XHR, so jsonP can only use get to pass Parameters.

Nowadays, Mobile apps are becoming increasingly popular. Thanks to HTML5, Mobile Web, and even the Hybird App, the App is gradually on the Web page of the local file system, there is also a need to obtain external data, and these requirements must also be cross-origin. HTML5 also comes with a new feature called "Cross-Origin Resource Sharing" to give developers the power to determine whether resources are allowed to be accessed across domains.

How can this problem be solved?
CORS, CrossOrigin Resources Sharing, that is, cross-source resource Sharing, is a feature of HTML5. It defines a way for the browser to interact with the server to determine whether cross-origin requests are allowed.

The server adds a special Header [Access-Control-Allow-Origin] to inform the client of cross-Origin restrictions. If the browser supports CORS, if the Origin is determined to pass, XHR requests are allowed without using jsonP or proxy files.

Use this Header to return the source domain that is allowed to request cross-origin requests. For example, the following Header is set for the website duelist.cn.
Access-Control-Allow-Origin: http://smdcn.net
With this setting, ajax requests to duelist.cn are allowed through pages under the http://smdcn.net, and other websites are still blocked from duelist.cn, in which way the website owner can restrict it on its own.

If you do not want to restrict the source, you can use
Access-Control-Allow-Origin :*
To allow any site to make cross-origin requests for this resource.


Solutions in 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;@Componentpublic 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-Methods", "POST, GET, OPTIONS, DELETE");        response.setHeader("Access-Control-Max-Age", "3600");        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");        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 code:

        $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) {                    });




Spring guide: https://spring.io/guides/gs/rest-service-cors/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.