Java – Register a Servlet in Spring Boot

The below code shows you how to register a Servlet in Spring Boot application via ServletRegistrationBean bean.

SpringBootWebApplication.java
package com.bytenota.springboot;

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

import com.bytenota.springboot.web.MyServlet;

@SpringBootApplication
public class SpringBootWebApplication {
	
   public static void main(String[] args) {
      SpringApplication.run(SpringBootWebApplication.class, args);
   }
   
   @Bean
   ServletRegistrationBean myServletRegistration () {
     ServletRegistrationBean srb = new ServletRegistrationBean();
     srb.setServlet(new MyServlet());
     srb.addUrlMappings("/my-servlet");
     return srb;
   }
   
}

In the above code, we have registered MyServlet and add URL mapping (/my-servlet) for it.

Leave a Reply

avatar