Spring Boot registration

Spring Boot provides ServletRegistrationBean FilterRegistrationBean, ServletListenerRegistrationBean three classes for the registration Servlet respectively, Filter, Listener, the following is sample code for servlets.

import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; Public class RegisterServlet extends HttpServlet {@override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { String name = getServletConfig().getInitParameter("name");
        String sex = getServletConfig().getInitParameter("sex");
        resp.getOutputStream().println("name is " + name);
        resp.getOutputStream().println("sex is " + sex);
    }
}
@Bean
public ServletRegistrationBean registerServlet() {
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
            new RegisterServlet(), "/registerServlet");
    servletRegistrationBean.addInitParameter("name"."javastack");
    servletRegistrationBean.addInitParameter("sex"."man");
    return servletRegistrationBean;
}
Copy the code

Component scan registration

Before Servlet 3.0, servlets, filters, and listeners were all configured in web.xml. After 3.0, web.xml is no longer required. All components can be configured through code or annotations.

As shown below, a screenshot is taken from Servlet 3.1.


Servlet 3.0 starts with these three annotations instead.

@webServlet => Replace servlet configuration

@webfilter => Replace the filter configuration

@webListener => Replace the listener configuration

Example configuration Servlet

import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Java technology stack */ @webServlet (name ="javaServlet", urlPatterns = "/javastack.cn", asyncSupported = true,
        initParams = {
        @WebInitParam(name = "name", value = "javastack"),
        @WebInitParam(name = "sex", value = "man") })
public class JavaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = getServletConfig().getInitParameter("name");
        String sex = getServletConfig().getInitParameter("sex");
        resp.getOutputStream().println("name is " + name);
        resp.getOutputStream().println("sex is "+ sex); }}Copy the code

Example for Configuring Filter

/** * @author Java technology stack */ @webfilter (filterName ="javaFilter", urlPatterns = "/ *", initParams = {
        @WebInitParam(name = "name", value = "javastack"),
        @WebInitParam(name = "code", value = "123456") })
public class JavaFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("java filter init.");
        String name = filterConfig.getInitParameter("name");
        String code = filterConfig.getInitParameter("code");
        System.out.println("name is " + name);
        System.out.println("code is " + code);
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("java filter processing.");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
        System.out.println("java filter destroy."); }}Copy the code

The Listener configuration is similar. The above example code is easy to understand and will not be detailed here.

It is important to note that for the sake of safety, the inside of the embedded server does not directly implement the Servlet 3.0 javax.mail. Servlet. ServletContainerInitializer interface, Or the Spring in the org. Springframework. Web. WebApplicationInitializer interface, otherwise it will lead to termination of the Spring applications Boot.

So, if you are using a Spring Boot embedded server, you need to add an additional @ServletComponentScan annotation to the configuration class to enable Servlet component scanning. If you are using a standalone server, you do not need to add it. The automatic discovery mechanism inside the server is used.

Dynamic registration

If you want to initialize servlets, filters, and listeners in Spring Boot, you need to implement the following interface in Spring and register it as a bean.

org.springframework.boot.web.servlet.ServletContextInitializer

ServletContext provides several methods for dynamic registration, as shown below.


The following is sample code for adding a Servlet dynamically.

import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Java technology stack */ @webServlet (name ="javaServlet", urlPatterns = "/javastack.cn", asyncSupported = true,
        initParams = {
        @WebInitParam(name = "name", value = "javastack"),
        @WebInitParam(name = "sex", value = "man") })
public class JavaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = getServletConfig().getInitParameter("name");
        String sex = getServletConfig().getInitParameter("sex");
        resp.getOutputStream().println("name is " + name);
        resp.getOutputStream().println("sex is "+ sex); } } import cn.javastack.springbootbestpractice.servlet.InitServlet; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.stereotype.Component; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; / * * * @ author Java technology stack * / @ Component public class ServletConfig implements ServletContextInitializer {@ Override public void onStartup(ServletContext servletContext) { ServletRegistration initServlet = servletContext .addServlet("initServlet", InitServlet.class);
        initServlet.addMapping("/initServlet");
        initServlet.setInitParameter("name"."javastack");
        initServlet.setInitParameter("sex"."man"); }}Copy the code

conclusion

This article introduces three ways to register servlets, filters and listeners under Spring Boot.

Welcome Java engineers who have worked for one to five years to join Java Programmer development: 721575865

Group provides free Java architecture learning materials (which have high availability, high concurrency, high performance and distributed, Jvm performance tuning, Spring source code, MyBatis, Netty, Redis, Kafka, Mysql, Zookeeper, Tomcat, Docker, Dubbo, multiple knowledge architecture data, such as the Nginx) reasonable use their every minute and second time to learn to improve yourself, don’t use “no time” to hide his ideas on the lazy! While young, hard to fight, to the future of their own account!