Spring CORSFilter - OncePerRequestFilter Example

Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page to make AJAX requests to another domain, different from the domain from where it originated.

CORS capability works by adding some specific HTTP headers that tell the browser that the downloaded webpage should be allowed to make web requests to given/all domains.

Spring CORSFilter.java

Below snippet shows how to handle CORS in spring-based applications using Filter. 
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.web.filter.OncePerRequestFilter;

public class CORSFilter extends OncePerRequestFilter {

    public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin";
    public static final String ALLOW_METHODS = "Access-Control-Allow-Methods";
    public static final String MAX_AGE = "Access-Control-Max-Age";
    public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers";
    public static final String ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";

    private String allowOrigins;
    private String allowMethods;
    private String maxAge;
    private String allowHeaders;
    private String allowCredentials;
    private boolean disableCORS = false;

    public void destroy() {


    public void setAllowOrigins(final String allowOrigins) {
        this.allowOrigins = allowOrigins;

    public void setAllowMethods(final String allowMethods) {
        this.allowMethods = allowMethods;

    public void setMaxAge(final String maxAge) {
        this.maxAge = maxAge;

    public void setAllowHeaders(final String allowHeaders) {
        this.allowHeaders = allowHeaders;

    public void setAllowCredentials(final String allowCredentials) {
        this.allowCredentials = allowCredentials;

    public void setDisableCORS(final boolean disableCORS) {
        this.disableCORS = disableCORS;

    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {
        final HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
        if (!disableCORS) {
            responseWrapper.addHeader(ALLOW_ORIGIN, allowOrigins);
            responseWrapper.addHeader(ALLOW_METHODS, allowMethods);
            responseWrapper.addHeader(MAX_AGE, maxAge);
            responseWrapper.addHeader(ALLOW_HEADERS, allowHeaders);
            responseWrapper.addHeader(ALLOW_CREDENTIALS, allowCredentials);
        filterChain.doFilter(request, responseWrapper);


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course