Java – Create a Custom CORS Filter

The below code example shows you how to create a custom CORS filter and add it to web.xml.

1. Create a custom CORS filter

CORSFilter.java
package com.bytenota.web.servlet.filter;

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;


public class CORSFilter implements Filter {
    
    public CORSFilter() {
    }    
  
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse resp = (HttpServletResponse) response;
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "GET, POST");
        resp.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

        chain.doFilter(request, response);
    }

    
    @Override
    public void destroy() {        
    }

    @Override
    public void init(FilterConfig filterConfig) {        
    }
    
}

We create custom CORSFilter class implementing the servlet Filter interface and then add some specific HTTP headers in the doFilter method.

 

2. Add the custom CORS filter to web.xml

web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">

    <filter>
        <filter-name>CORSFilter</filter-name>
        <filter-class>com.bytenota.web.servlet.filter.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CORSFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    [...]
</web-app>
0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x