CORS cross-domain request: front-end and back-end separation

1. Request filter:

/**
 * OncePerRequestFilter guarantees that a request is executed only once in any servlet container.
*/
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        Properties props = PropertiesLoaderUtils.loadAllProperties("cors.properties");
        // Allowed client domains
        response.addHeader("Access-Control-Allow-Origin", props.getProperty("cors.allowed-origins"));
        // allowable method names
        response.addHeader("Access-Control-Allow-Methods", props.getProperty("cors.allowed-methods"));
        //The client request header that allows the server to access, multiple request headers are separated by commas, for example: Content-Type
        response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token");
        //Pre-check request time
        response.addHeader("Access-Control-Max-Age", props.getProperty("cors.max-age"));//30 min
        response.addHeader("Access-Control-Allow-Credentials", "true");

        filterChain.doFilter(request, response);
    }

}

 

2. Configure cross-domain filters in web.xml:

 

<!--Configure filters for cross-domain requests-->
	<filter>
		<filter-name>cors</filter-name>
		<filter-class>com.jd.dashboard.cors.CrossFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>cors</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

 

3. The properties in the filter are configured as follows:

 

The property configuration file is as follows: cors.properties

# Cross-domain request CORS global configuration attribute value

	#Client domain name allowed to access, for example: http://web.xxx.com
	cors.allowed-origins=http://front.xx.com

	#Name of the method to allow access
	cors.allowed-methods=POST, GET, OPTIONS, DELETE

	#Client request headers that allow server access, multiple request headers are separated by commas, for example: Content-Type
	cors.allowed-headers=Content-Type

	#Server response headers that allow client access
	cors.exposed-headers=

	#Whether to allow requests with authentication information, if you want to get the cookie under the client domain, you need to set it to true
	cors.allow-credentials=true

	cors.max-age=1800

 

 

Since jsonp only supports GET requests, this method is recommended.

Guess you like

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