Servlet - Servlet with Tomcat CorsFilter example

[Updated: Apr 14, 2017, Created: Apr 14, 2017]

In this example, we will learn how make use of Tomcat CorsFilter to enable ready to use CORS functionality.

We are going to use two web applications, both running on localhost but on two different ports.

The origin application

We are going to use the same origin application from the last example.

The cross domain target application

We are going to run this application at the default port 8080.

We need to add tomcat API dependency so that we can register org.apache.catalina.filters.CorsFilter.


<project .....>


Registering the filter:

public class MyContextListener implements ServletContextListener {

  public void contextInitialized(ServletContextEvent sce) {
      FilterRegistration.Dynamic fr = sce.getServletContext()
                                         .addFilter("tomcatCorsFilter", CorsFilter.class);
      EnumSet<DispatcherType> disps = EnumSet.of(
              DispatcherType.REQUEST, DispatcherType.FORWARD);
      fr.addMappingForUrlPatterns(disps, false, "/*");
      fr.setInitParameter(CorsFilter.PARAM_CORS_ALLOWED_ORIGINS, "http://localhost:9000");

  public void contextDestroyed(ServletContextEvent sce) {

PARAM_CORS_ALLOWED_ORIGINS is used to set the allowed external origins . A * can be specified to enable access to this application resources from any origin. Or we can provide a comma separated allowed origins. In above code. we are allowing only http://localhost:9000 (don't put slash / at the end).

Let's write a simple servlet which will represent a resource at post 8080.

@WebServlet(name = "myServlet", urlPatterns = {"/test"},
      asyncSupported = true)
public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      PrintWriter writer = resp.getWriter();
      writer.write("test response from myServlet");

Running the applications

Run both applications one by one:

mvn tomcat7:run

Access the static page served by the first application:

Click on 'Make Ajax Call':

Example Project

Dependencies and Technologies Used :

  • javax.servlet-api 3.1.0 Java Servlet API
  • tomcat-catalina 8.5.13: Tomcat Servlet Engine Core Classes and Standard implementations.
  • JDK 1.8
  • Maven 3.3.9

Cross Tomcat Filter Example Select All Download
  • servlet-cors-with-tomcat-filter
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also