Spring Mvc+Angular JS implements cross-domain solution through CORS

Posted by eroticheretic on Wed, 19 Jun 2019 22:33:18 +0200

Original: http://www.cnblogs.com/tanghaiyang/p/4375601.html
Theme Spring MVC Angular JS
What is the cross-domain request problem?


The reason for this problem is that modern browsers default to prevent cross-domain ajax requests for security reasons, which is a necessary function in modern browsers, but often inconvenient to development.


But cross-domain needs have always been there. In order to cross-domain, hard-working and brave program apes have come up with a lot of methods, such as jsonP, proxy files and so on. But these practices add a lot of unnecessary maintenance costs, and application scenarios also have many limitations, such as jsonP is not XHR, so jsonP can only use GET to pass parameters.


With the advent of mobile applications, HTML5, Mobile Web and even Hybird App are becoming popular. There is also a need to obtain external data on the Web pages of the local file system, which is bound to be cross-domain. At the same time, HTML5 brings a new feature called Cross-Origin Resource Sharing, which gives developers the power to decide whether resources are allowed to be accessed across domains.


How to solve it?


CORS, CrossOrigin Resources Sharing, or cross-source resource sharing, is a feature of HTML5, which defines a way for browsers and servers to interact to determine whether cross-domain requests are allowed.


By adding a special Header[Access-Control-Allow-Origin] to the server to inform the client of cross-domain restrictions, if the browser supports CORS, and if Origin is judged to pass, XHR will be allowed to make requests without using jsonP or proxy files.


Use this Header to return to the source domain where cross-domain requests are allowed, such as duelist.cn, where the following Header is set


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


After this setup, ajax requests for duelist.cn will be allowed through the pages under http://smdcn.net, while duelist.cn will still be blocked by other websites, through which website owners can restrict themselves.


Of course, if you don't want to limit sources, you can


Access-Control-Allow-Origin: *


To allow any site to make cross-domain requests for this resource


Solutions under Spring MVC:


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", "*");   //The default URI (url)
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  //Approaches to cross-domain request permission
		response.setHeader("Access-Control-Max-Age", "3600");   //Maximum cached value
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		chain.doFilter(req, res);  //Execution chain of filter
	}
	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 End 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) {
 });

Topics: html5 Spring Mobile JSON