Spring Boot @WebServlet Annotation Example

John Doe ·

1524 Views

TestServlet.java

package com.blood.money.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet(
	name = "Example",
	description = "Example Servlet",
	urlPatterns = {"/Example"}
)
public class TestServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
         
        String html = "<html>";
        html += "<body>";      
        html += "<div>THIS IS NOT A TEST</div>";
        html += "</body>";
        html += "</html>";
         
        writer.println(html);
    }
}

 

How do I get Spring Boot to auto-load all @WebServlet annotated servlets and honor their url mappings?

Add @ServletComponentScan in your bootstrap class.

such as

@SpringBootApplication
@ServletComponentScan
public class BadApplication {

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

}

 

spring Servlet