Close

Servlet - Servlet with Tomcat CorsFilter example

[Last Updated: Mar 8, 2018]

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.

pom.xml

<project .....>
<modelVersion>4.0.0</modelVersion>
<groupId>com.logicbig.example</groupId>
<artifactId>servlet-cors-with-tomcat-filter</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>8.5.13</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>

Registering the filter

@WebListener
public class MyContextListener implements ServletContextListener {

  @Override
  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");
  }

  @Override
  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 {

  @Override
  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
                • MyServlet.java

    See Also