SpringBoot之配置嵌入式Servlet容器

1、SpringBoot默认使用Tomcat作为嵌入式的Servlet容器;

2、如何定制和修改Servlet容器的相关配置;有两种方式

    1).修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】);

spring.mvc.date-format=yyyy-MM-dd
spring.thymeleaf.cache=false 
spring.messages.basename=i18n.login

server.port=8081
server.context-path=/crud
server.tomcat.uri-encoding=UTF-8

通用的Servlet容器设置server.xxx    Tomcat的设置server.tomcat.xxx

    2).编写一个**EmbeddedServletContainerCustomizer**:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置

SpringBoot之配置嵌入式Servlet容器_第1张图片

3、注册servlet三大组件:servlet,filter,listener 

MyServlet:

SpringBoot之配置嵌入式Servlet容器_第2张图片

MyFilter:过滤器

SpringBoot之配置嵌入式Servlet容器_第3张图片

MyListener:监听器

SpringBoot之配置嵌入式Servlet容器_第4张图片

由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。注册三大组件用以下方式ServletRegistrationBean,FilterRegistrationBean,ServletListenerRegistrationBean

@Configuration
public class MyServerConfig {
   //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet(){
        //映射/myServlet请求
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }
    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return registrationBean;
    }
    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }
    //配置嵌入式的Servlet容器
    @Bean
    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
        return new EmbeddedServletContainerCustomizer() {
            //定制嵌入式的Servlet容器相关的规则
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.setPort(8083);
            }
        };
    }

}

SpringBoot在配置SpringMVC的时候,自动的注册SpringMVC的前端控制器:DIspatcherServlet;所以不用配了

参考DispatcherServletAutoConfiguration类源码:

4、替换为其他嵌入式Servlet容器

默认为tomcat:


   org.springframework.boot
   spring-boot-starter-web
   引入web模块默认就是使用嵌入式的Tomcat作为Servlet容器;

Jetty:



   org.springframework.boot
   spring-boot-starter-web
   
      
         spring-boot-starter-tomcat
         org.springframework.boot
      
   




   spring-boot-starter-jetty
   org.springframework.boot

Undertow:



   org.springframework.boot
   spring-boot-starter-web
   
      
         spring-boot-starter-tomcat
         org.springframework.boot
      
   




   spring-boot-starter-undertow
   org.springframework.boot

 

你可能感兴趣的:(Spring,Boot)