[JAVA] Spring Boot Servlet mapping

On this page, we'll look at an example of a Spring Boot Servlet mapping. Servlet mapping can be achieved by using ServletRegistrationBean or by using @ServletComponentScan annotation of Spring Boot. The ServletRegistrationBean registers the Servlet as a Spring Bean. @ServletComponentScan scans Servlets annotated with @WebServlet. The annotation @ServletComponentScan only works with Spring Boot's built-in server. On this page, we will create two Servlets and one Spring Controller class. The following is an example of using Servlet in stages using ServletRegistrationBean and @ServletComponentScan.

Prerequisites

  1. Java 9
  2. Spring 5.0.7.RELEASE
  3. Spring Boot 2.0.3.RELEASE
  4. Maven 3.5.2
  5. Eclipse Oxygen

pom.xml

pom.xml


	<?xml version="1.0" encoding="UTF-8"?>
	<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.concretepage</groupId>
		<artifactId>spring-boot-app</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<packaging>jar</packaging>
		<name>spring-boot-app</name>
		<description>Spring Boot Application</description>

		<parent>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-parent</artifactId>
			<version>2.0.3.RELEASE</version>
			<relativePath/>
		</parent>
		<properties>
			<java.version>9</java.version>
		</properties>
		<dependencies>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-web</artifactId>
			</dependency>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-devtools</artifactId>
				<optional>true</optional>
			</dependency>
		</dependencies> 
		
		<build>
			<plugins>
				<plugin>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-maven-plugin</artifactId>
				</plugin>
			</plugins>
		</build>
	</project> 

Register the Servlet as a Spring Bean using the ServletRegistrationBean

The ServletRegistrationBean is used to register a Servlet in a Servlet 3.0 or later container. You need to create a Bean for the ServletRegistrationBean in JavaConfig. Find some methods of the ServletRegistrationBean used to configure the Servlet.

** setServlet () **: Set the Servlet to be registered. ** addUrlMappings () **: Add URL mappings for the Servlet. ** setLoadOnStartup **: Sets the priority for loading Servlets at startup.

I have two Servlets, HelloCountryServlet and HelloStateServlet, and I use the ServletRegistrationBean to register them in Spring Boot as follows:

WebConfig.java


	package com.concretepage;
	import javax.servlet.http.HttpServlet;
	import org.springframework.boot.web.servlet.ServletRegistrationBean;
	import org.springframework.context.annotation.Bean;
	import org.springframework.context.annotation.Configuration;
	import com.concretepage.servlets.HelloCountryServlet;
	import com.concretepage.servlets.HelloStateServlet;

	@Configuration
	public class WebConfig {
	   @Bean	
	   public ServletRegistrationBean<HttpServlet> countryServlet() {
		   ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
		   servRegBean.setServlet(new HelloCountryServlet());
		   servRegBean.addUrlMappings("/country/*");
		   servRegBean.setLoadOnStartup(1);
		   return servRegBean;
	   }
	   @Bean	
	   public ServletRegistrationBean<HttpServlet> stateServlet() {
		   ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
		   servRegBean.setServlet(new HelloStateServlet());
		   servRegBean.addUrlMappings("/state/*");
		   servRegBean.setLoadOnStartup(1);
		   return servRegBean;
	   }   
	} 

Create a ServletRegistrationBean bean for all Servlets. The Servlets HelloCountryServlet and HelloStateServlet can be accessed using the URLs ** / country ** and ** / state **, respectively. Find the Servlet used in this example.

HelloCountryServlet.java


	package com.concretepage.servlets;
	import java.io.IOException;
	import java.io.PrintWriter;
	import javax.servlet.http.HttpServlet;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	public class HelloCountryServlet extends HttpServlet   {
		private static final long serialVersionUID = 1L;
		public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		    doGet(request,response);
		}
	        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	            response.setContentType("text/html");
	            PrintWriter out = response.getWriter();
		    out.println("<h3>Hello India!</h3>");	
		}
	} 

HelloStateServlet.java


	package com.concretepage.servlets;
	import java.io.IOException;
	import java.io.PrintWriter;
	import javax.servlet.http.HttpServlet;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	public class HelloStateServlet extends HttpServlet   {
		private static final long serialVersionUID = 1L;
		public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		   doGet(request,response);
		}
	        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	           response.setContentType("text/html");
	           PrintWriter out = response.getWriter();
		   out.println("<h3>Hello Uttar Pradesh!</h3>");	
		}
	} 

The controller used in this example.

HelloWorldController.java


	package com.concretepage.controller;
	import org.springframework.web.bind.annotation.RequestMapping;
	import org.springframework.web.bind.annotation.RestController;

	@RestController
	public class HelloWorldController {     
		
	    @RequestMapping("/world")
	    public String helloMsg() {
	    	String msg = "Hello World!";
	        return msg;
	    }
	} 

Main class for launching applications.

SpringBootAppStarter.java


	package com.concretepage;
	import org.springframework.boot.SpringApplication;
	import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Example of Servlet using @ServletComponentScan

Spring Boot's @ServletComponentScan scans @WebServlet-annotated Servlets, @WebFilter-annotated filters, and @WebListener-annotated Listeners. The annotation @ServletComponentScan is used at the JavaConfig class level. @ServletComponentScan scans Servlets, filters, and listeners only using an embedded web server. It is a Servlet with @WebServlet annotation.

HelloCountryServlet.java


	package com.concretepage.servlets;
	import java.io.IOException;
	import java.io.PrintWriter;
	import javax.servlet.annotation.WebServlet;
	import javax.servlet.http.HttpServlet;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	@WebServlet(urlPatterns = "/country/*", loadOnStartup = 1)
	public class HelloCountryServlet extends HttpServlet   {
		private static final long serialVersionUID = 1L;
		public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		     doGet(request,response);
		}
	        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	             response.setContentType("text/html");
	             PrintWriter out = response.getWriter();
		     out.println("<h3>Hello India!</h3>");	
		}
	} 

HelloStateServlet.java


	package com.concretepage.servlets;
	import java.io.IOException;
	import java.io.PrintWriter;
	import javax.servlet.annotation.WebServlet;
	import javax.servlet.http.HttpServlet;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	@WebServlet(urlPatterns = "/state/*", loadOnStartup = 1)
	public class HelloStateServlet extends HttpServlet   {
		private static final long serialVersionUID = 1L;
		public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		    doGet(request,response);
		}
	        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	            response.setContentType("text/html");
	            PrintWriter out = response.getWriter();
		    out.println("<h3>Hello Uttar Pradesh!</h3>");	
		}
	} 

You can use @ServletComponentScan as follows:

SpringBootAppStarter.java


	package com.concretepage;
	import org.springframework.boot.SpringApplication;
	import org.springframework.boot.autoconfigure.SpringBootApplication;
	import org.springframework.boot.web.servlet.ServletComponentScan;

	@ServletComponentScan
	@SpringBootApplication
	public class SpringBootAppStarter {
	    public static void main(String[] args) {
	        SpringApplication.run(SpringBootAppStarter.class, args);
	    }
	} 

Test application

You can run the Spring Boot application in the following ways:

	mvn spring-boot:run
	mvn clean eclipse:eclipse

Click and then update the project in eclipse. Click Run as-> Java Application to run the main class SpringBootAppStarter. Then the Tomcat server is started.

	mvn clean package

Get the executable JAR ** spring-boot-app-0.0.1-SNAPSHOT.jar ** in the target folder. Run this JAR as follows:

	java -jar target / spring-boot-app-0.0.1-SNAPSHOT.jar

The Tomcat server is started.

Now you are ready to test your application.

The URL to execute HelloCountryServlet.

http://localhost:8080/country

The URL to execute HelloStateServlet.

http://localhost:8080/state

The URL to execute the HelloWorldController method.

http://localhost:8080/world

References

Spring Boot Reference Guide ServletRegistrationBean @ServletComponentScan

Translation source site

Spring Boot Servlet Mapping

Recommended Posts

Spring Boot Servlet mapping
Challenge Spring Boot
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
SPRING BOOT learning record 01
Spring Boot + Heroku Postgres
Spring boot memo writing (1)
First Spring Boot (DI)
SPRING BOOT learning record 02
Spring Boot2 cheat sheet
Spring Boot exception handling
Spring boot development-development environment-
Spring Boot learning procedure
Use Servlet filter in Spring Boot [Spring Boot 1.x, 2.x compatible]
Learning Spring Boot [Beginning]
Spring boot memo writing (2)
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
[Spring Boot] Environment construction (macOS)
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Spring Boot tutorial task schedule
Spring 5 & Spring Boot 2 Hands-on preparation procedure
Get started with Spring boot
Hello World with Spring Boot!
Spring Boot 2 multi-project in Gradle
[Spring Boot] Web application creation
spring boot port duplication problem
Spring Boot Hot Swapping settings
[Java] Thymeleaf Basic (Spring Boot)
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use
Spring Boot DB related tips
Hello World with Spring Boot
Set cookies with Spring Boot
[Spring Boot] Easy paging recipe
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Major changes in Spring Boot 1.5
Add module with Spring Boot
Getting Started with Spring Boot
NoHttpResponseException in Spring Boot + WireMock
[Spring Boot] Send an email
Spring Boot performance related settings
Introduction to Spring Boot Part 1
Spring Boot External setting priority
Try using Spring Boot Security
[Java] [Spring] Spring Boot 1.4-> 1.2 Downgrade Note
Try Spring Boot on Mac