Spring Boot - Using Servlet, Filter and Listener example 1

Posted on December 9, 2017


In Spring Boot application, Servlet, Filter and listener are registered either as a Spring @Bean or by scanning the @WebServlet, @WebFilter and @WebListener annotated classes with an embedded container. 

This post shows you how to use the Servlet, Filter and listener in Spring Boot application by registering them as a @Bean.

You can use the ServletRegistrationBean, FilterRegistrationBean and ServletListenerRegistrationBean classes to register the Servlet, Filter and listener respectively.

Tools and technologies used for this application are -

  • Spring Boot 1.5.9.RELEASE
  • Java SE 1.8
  • Maven 3.5.2
  • Eclipse Neon.3 (4.6.3)

Project structure

Final project structure of our application will look like as follows.

spring-boot-servlet-filter-example1.PNG

Jar dependencies

Edit pom.xml file of your maven project and add the spring-boot-starter-web dependency in it.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.boraji.tutorial.springboot</groupId>
  <artifactId>spring-boot-servlet-filter-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Spring Boot - Servlet, Filter and  Listener example</name>
  <packaging>war</packaging>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Creating Servlet, Filter and Listener

Create a Servlet class under com.boraji.tutorial.springboot.servlet package.

MyServlet.java

package com.boraji.tutorial.springboot.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("MyServlet's doGet() method is invoked.");
    doAction(req, resp);
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println("MyServlet's doPost() method is invoked.");
    doAction(req, resp);
  }
  
  private void doAction(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String name = req.getParameter("name");
    resp.setContentType("text/plain");
    resp.getWriter().write("Hello " + name + "!");
  }
  
}

 

Create a Filter class under com.boraji.tutorial.springboot.filter package.

MyFilter.java

package com.boraji.tutorial.springboot.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilter implements Filter {

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    
    System.out.println("MyFilter doFilter() is invoked.");
    Enumeration<String> params = req.getParameterNames();
    while (params.hasMoreElements()) {
      String param=params.nextElement();
      System.out.println("Parameter:"+param+"\tValue:"+req.getParameter(param));
    }
    chain.doFilter(req, res);
  }

  @Override
  public void init(FilterConfig config) throws ServletException {
    
  }

  @Override
  public void destroy() {

  }

}

Create a Servlet context listener class under com.boraji.tutorial.springboot.listener package.

MyServletContextListener.java

package com.boraji.tutorial.springboot.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener {
  @Override
  public void contextInitialized(ServletContextEvent e) {
    System.out.println("MyServletContextListener Context Initialized");
  }

  @Override
  public void contextDestroyed(ServletContextEvent e) {
    System.out.println("MyServletContextListener Context Destroyed");
  }

}

Registering Servlet, Filter and Listener

As already stated, Servlet, Filter and listener can be registered as bean using the ServletRegistrationBean, FilterRegistrationBean and ServletListenerRegistrationBean classes.

So, create a SpringBootApp class and declare the ServletRegistrationBean, FilterRegistrationBean and ServletListenerRegistrationBean bean methods as follows.

SpringBootApp.java

package com.boraji.tutorial.springboot;

import javax.servlet.ServletContextListener;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.boraji.tutorial.springboot.filter.MyFilter;
import com.boraji.tutorial.springboot.listener.MyServletContextListener;
import com.boraji.tutorial.springboot.servlet.MyServlet;

@SpringBootApplication
public class SpringBootApp {

  // Register Servlet
  @Bean
  public ServletRegistrationBean servletRegistrationBean() {
    ServletRegistrationBean bean = new ServletRegistrationBean(
        new MyServlet(), "/myServlet");
    return bean;
  }

  // Register Filter
  @Bean
  public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean bean = new FilterRegistrationBean(new MyFilter());
    // Mapping filter to a Servlet
    bean.addServletRegistrationBeans(new ServletRegistrationBean[] {
          servletRegistrationBean() 
       });
    return bean;
  }

  // Register ServletContextListener
  @Bean
  public ServletListenerRegistrationBean<ServletContextListener> listenerRegistrationBean() {
    ServletListenerRegistrationBean<ServletContextListener> bean = 
        new ServletListenerRegistrationBean<>();
    bean.setListener(new MyServletContextListener());
    return bean;

  }

  public static void main(String[] args) {
    SpringApplication.run(SpringBootApp.class, args);
  }

}

 

Run application

Run the SpringBootApp.java class as Java application i.e. go to Run→ Run as → Java Application

Or, you can use the mvn spring-boot:run command to run the spring boot application.

After executing the main class, enter the URL http://localhost:8080/myServlet?name=Sunil%20Singh%20Bora in browser's address bar.

spring-boot-servlet-filter-example1_01.PNG

 Your console output will look like as follows.

spring-boot-servlet-filter-example1_02.PNG