天天看点

SpringBoot配置自定义Servlet

目录

一、前言

二、准备工作

三、开始配置

配置文件配置

注解自动扫描

四、测试运行

一、前言

DispatcherServlet是SpringMVC处理请求的默认Servlet,当有需求自己写一个Servlet来处理请求,可有以下两种方式配置:

(传统web.xml配置方式不做赘述。此处为SpringBoot配置方式)

  1. 配置文件配置
  2. 注解自动扫描

二、准备工作

加入web依赖

<dependency>
 		<groupId>org.springframework.boot</groupId>
  	    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
           

创建MyServlet,并继承HttpServlet,重写doGet方法

public class MyDispatcherServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("GET方法进入MyServlet");
    }
}
           

三、开始配置

配置文件配置

@Configuration注解:用于定义配置类,替换传统的xml配置

@Bean:方法级别注解,必须在@Configuration注解类下使用,被该注解标记的方法 其返回Bean会被Spring容器托管。

新建WebConfig类,在类上使用@Configuration注解,使用ServletRegistrationBean类进行Servlet注册。

@Configuration
public class WebConfig {

    @Bean
    public ServletRegistrationBean registerMyServlet(){
        return new ServletRegistrationBean(new MyServlet());
    }
}
           

 查看ServletRegistrationBean类源码,可以看到第一行的类注释:将一个Servlet注册到Servlet3.0+容器。

package org.springframework.boot.web.servlet;

/**
 * A {@link ServletContextInitializer} to register {@link Servlet}s in a Servlet 3.0+
 * container. Similar to the {@link ServletContext#addServlet(String, Servlet)
 * registration} features provided by {@link ServletContext} but with a Spring Bean
 * friendly design.
 * <p>
 * The {@link #setServlet(Servlet) servlet} must be specified before calling
 * {@link #onStartup}. URL mapping can be configured used {@link #setUrlMappings} or
 * omitted when mapping to '/*' (unless
 * {@link #ServletRegistrationBean(Servlet, boolean, String...) alwaysMapUrl} is set to
 * {@code false}). The servlet name will be deduced if not specified.
 *
 * @param <T> the type of the {@link Servlet} to register
 * @author Phillip Webb
 * @since 1.4.0
 * @see ServletContextInitializer
 * @see ServletContext#addServlet(String, Servlet)
 */
public class ServletRegistrationBean<T extends Servlet> extends DynamicRegistrationBean<ServletRegistration.Dynamic> {
           

注解自动扫描

在MyServlet类上增加@WebServlet注解

@WebServlet
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException{
        System.out.println("GET方法进入MyServlet");
    }
}
           

然后在配置类上增加@ServletComponentScan注解,放在启动类上比较方便,无需配置扫描路径(不配置路径默认扫描当前路径类及其子路径类)。

@ServletComponentScan
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) throws Exception{
        SpringApplication.run(DemoApplication.class, args);
        System.out.println("============ project start success ============");
    }

}
           

四、测试运行

 在postman随便发起一个GET请求,例如:http://127.0.0.1:8080/test/query

查看打印日志:

SpringBoot配置自定义Servlet