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
package com.bytenota.web.servlet.filter;

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() {
    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);

    public void destroy() {        

    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-app xmlns="" version="2.5">