Handle CORS problem using java (Servlet/Filter)

Handle CORS problem using java (Servlet/Filter)

1. Make a Filter to handle all CORS request

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class CORSFilter
 */
public class CORSFilter implements Filter {

   
    public CORSFilter() {
        // TODO Auto-generated constructor stub
    }

   
    public void destroy() {
        // TODO Auto-generated method stub
    }

   
   
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
    
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Methods","GET,POST");
        resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, access-token");

        // Just ACCEPT and reply OK if OPTIONS for prefetch request
        if ( request.getMethod().equals("OPTIONS") ) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
2. Use this filter in web.xml
<filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>com.example.web.servlets.CORSFilter</filter-class>
    </filter>
   
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Now you can use all request in another application where it will by pass CORS errors.

Comments

Popular posts from this blog

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'

Upload csv file at Google Cloud Storage using java

Read Images from a xlsx file using Apache POI