Java Server-side CORS Cross-Domain Configuration

Now the web program architecture tends to be more and more front-end and back-end separated, the benefits of front-end and back-end separated, not to mention here.But one of the problems we face is cross-domain.Here is a brief record of the solution on the server side.

References and references to relevant parts of this article http://blog.csdn.net/andong154564667/article/details/51508042

External jar package implementation

maven Join Dependency:

  <dependency>  
      <groupId>com.thetransactioncompany</groupId>  
      <artifactId>java-property-utils</artifactId>  
      <version>1.7.1</version>  
  </dependency>  
  <dependency>  
      <groupId>com.thetransactioncompany</groupId>  
      <artifactId>cors-filter</artifactId>  
      <version>2.5</version>  
  </dependency>  

Web.xmlConfiguration in:

    <filter>
        <description>Cross-domain filter</description>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedMethods</param-name>
            <param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Accept, Origin, X-Requested-With, Content-Type, fuserkey</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposedHeaders</param-name>
            <param-value>Set-Cookie</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>*.do</url-pattern>
    </filter-mapping>

Custom Filter Implementation

Filter configuration is based on servlet 3.0 annotations and requires servlet 3.0, tomcat 7 and above to have this package.Relevant configuration of Filter based on annotation, Servlet Baidu itself.

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Cross-domain filter
 *
 * Configuring Filter based on servlet 3.0 annotation
 * Serlet 3.0, Tomcat 7 and above are required for this package.
 * Execution order of multiple filter s, sorted by class name.
 *
 * @author yanfa.Chen
 * @date 2017/12/1
 */

@WebFilter(filterName = "corsFilter", value = {"*.do"})
public class CorsFilter implements Filter {
    /*
    Access-Control-Allow-Origin: Allow access to client domain names, such as:http://web.xxx.com, if *, it means that it can be accessed from any domain without any restrictions;
    Access-Control-Allow-Methods: Method names that are allowed to be accessed are separated by commas, such as GET,POST,PUT,DELETE,OPTIONS;
    Access-Control-Allow-Credentials: Whether requests are allowed with authentication information and need to be set to true to obtain cookie s under the client domain;
    Access-Control-Allow-Headers: Client request headers that allow service-side access, with multiple request headers separated by commas, for example, Content-Type;
    Access-Control-Expose-Headers: Server-side response headers that allow client access, with multiple response headers separated by commas.
    */

    /**
     * Allowed request sources, defaulting to all.
     * If you need to configure it to allow multiple domain names, you can use an array to set the origin of the current request to origin if it is included in the whitelist.
     */
    private final String allowOrigin = "*";
    /**
     * Method of allowing requests
     */
    private final String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
    private final String allowCredentials = "true";
    private final String allowHeaders = "Accept, Origin, X-Requested-With, Content-Type, fuserkey";
    private final String exposeHeaders = "Set-Cookie";

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String currentOrigin = request.getHeader("Origin");

        if(StringUtils.isNotEmpty(allowOrigin)){
            response.setHeader("Access-Control-Allow-Origin", allowOrigin);
        }

        response.setHeader("Access-Control-Allow-Methods", allowMethods);
        response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
        response.setHeader("Access-Control-Allow-Headers", allowHeaders);
        response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("CorsFilter Started");
    }

}

Tags: Tomcat Java Maven Apache

Posted on Tue, 14 Jul 2020 10:34:25 -0400 by jonasr