0%

SpringBoot-配置嵌入式Servlet容器

SpringBoot-配置嵌入式Servlet容器

SpringBoot默认使用的是嵌入式Servlet容器(Tomcat)

如何定制和修改Servlet容器的相关配置

  • 方法一:修改和server有关的配置(ServerProperties)
1
2
3
4
5
6
7
server.prot=8081
server.context-path=/test

# 通用的Servlet容器设置
server.xxx
# Tomcat设置
server.tomcat.xxx
  • 方法 二:编写一个WebServerFactoryCustomizer:嵌入式的Servlet容器定制器,来修改Servlet容器配置
1
2
3
4
5
6
7
8
9
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
factory.setPort(8081);
}
};
}

SpringBoot注册Servlet的三大组件

由于 SpringBoot默认以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml,所以注册三大组件方式为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 注册三大组件
* 分别对应的是:
* ServletRegistrationBean
* FilterRegistrationBean
* ServletListenerRegistrationBean
* @return
*/
@Bean
public ServletRegistrationBean myServlet(){
return new ServletRegistrationBean(new MyServlet(),"/myServlet");

}
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
@Bean
public ServletListenerRegistrationBean myListener(){
return new ServletRegistrationBean<MyListener>(new MyListener());
}

DispatcherServlet自动配置

默认拦截:/ 所有请求,包括静态资源,但不拦截jsp;/*会拦截jsp

可能通过server.servletPath来修改springMVC前端控制器默认拦截的请求路径

SpringBoot能否支持其它的Servlet容器

  • Jetty(长连接)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <exclusion>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <groupId>org.springframework.boot</groupId>
    </exclusion>
    </exclusions>
    </dependency>

    <dependency>
    <artifactId>spring-boot-starter-jetty</artifactId>
    <groupId>org.springframework.boot</groupId>
    </dependency>
  • Undertow(不支持JSP)

    配置与jetty类似

使用外置的Servlet容器

嵌入式Servlet容器:应用打包成可执行的jar

优点:简单、便携

缺点:默认不支持JSP、优化定制比较复杂

外置的Servlet容器:在应用外安装Tomcat--应用war包的方式打包

  1. 创建新项目时选择packaging为war,会自动将嵌入式的tomcat指定为privided且编写一个SpringBootServletInitializer的子类调用configure方法

  2. 在main文件夹下新建webapp文件夹

  3. 和之前的web工程一样配置tomcat启动即可

    1
    2
    3
    # 配置前后缀
    spring.mvc.view.prefix=/WEB_INF/
    spring.mvc.view.suffix=.jsp

启动原理

jar包:执行SpringBoot主类的main方法,启动IOC容器,创建嵌入式Servlet容器

war包:启动服务器,服务器启动SpringBoot应用,启动IOC容器

Servlet3.0中

规则:

  1. 服务器(web应用启动)会创建当前web应用里面的每一个jar包里面的ServletContainerInitializer实例
  2. ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer实现类的全类名
  3. 还可以使用@HandlersTypes,在应用启动的时候加载我们需要的类