【Spring Boot】(18)、Spring Boot配置嵌入式Servlet容器

版权声明:本文为博主原创文章,未经博主允许不得转载。请联系博主或者emailTo:412425870@qq.com,谢谢! https://blog.csdn.net/caychen/article/details/80344372

Spring Boot默认使用Tomcat作为嵌入式的Servlet容器,只要引入了spring-boot-start-web依赖,则默认是用Tomcat作为Servlet容器:


1、定制和修改Servlet容器的相关配置

1)、修改和server有关的配置(ServerProperties,它其实也是EmbeddedServletContainerCustomizer的子类):

server.port=8080
server.context-path=/

# tomcat相关设置
server.tomcat.uri-encoding=UTF-8

2)、编写EmbeddedServletContainerCustomizer(嵌入式的Servlet容器的定制器)来修改Servlet容器的配置,返回一个自定义的定制器Bean:

@Bean
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
    //定制嵌入式的Servlet容器相关的属性配置
    return container -> container.setPort(8083);
}


2、注册Servlet容器的三大组件(Servlet、Filter、Listener)

        由于Spring Boot默认是以jar包的形式启动嵌入式的Servlet容器,从而来启动Spring Boot的web应用,没有web.xml文件。

以前编写三大组件大多都需要在web.xml文件中进行配置(使用注解除外,@WebServlet@WebListener@WebFilter),而现在使用SpringBoot作为框架,如果需要编写三大组件,则需要使用配置的方式进行注册。

要注册三大组件:

  • ServletRegistrationBean:注册Servlet

//Servlet定义
public class MyServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("这是一个servlet请求...");
	}
}

//Servlet注册
@Configuration
public class MyServletConfig {

	//注册Servlet
	@Bean
	public ServletRegistrationBean myServlet(){
		return new ServletRegistrationBean(new MyServlet(), "/myServlet");
	}
}


  • FilterRegistrationBean:注册Filter
//Filter定义
public class MyFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("MyFilter process...");
		//放行
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}
}

//Filter注册
@Bean
public FilterRegistrationBean myFilter(){
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new MyFilter());
    bean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
    return bean;
}


  • ServletListenerRegistrationBean:注册Listener
//Listener定义
public class MyListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("contextInitialized...web启动");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("contextDestroyed...web销毁");
	}
}

//Listener注册
@Bean
public ServletListenerRegistrationBean myListener(){
    return new ServletListenerRegistrationBean<>(new MyListener());
}


    最熟悉的莫过于,在Spring Boot在自动配置SpringMVC的时候,会自动注册SpringMVC前端控制器:DispatcherServlet,该控制器主要在DispatcherServletAutoConfiguration自动配置类中进行注册的。

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass(DispatcherServlet.class)
@AutoConfigureAfter(EmbeddedServletContainerAutoConfiguration.class)
public class DispatcherServletAutoConfiguration {
    
    //other code...
    
    public static final String DEFAULT_DISPATCHER_SERVLET_BEAN_NAME = "dispatcherServlet";
    
    private String servletPath = "/";
    
    @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
                @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
    public ServletRegistrationBean dispatcherServletRegistration(
        DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(
            dispatcherServlet, this.serverProperties.getServletMapping());
        //默认拦截 / 所有请求,包括静态资源,但是不拦截jsp请求;/*会拦截jsp
        //可以通过修改server.servlet-path来修改默认的拦截请求
        registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
        registration.setLoadOnStartup(
            this.webMvcProperties.getServlet().getLoadOnStartup());
        if (this.multipartConfig != null) {
            registration.setMultipartConfig(this.multipartConfig);
        }
        return registration;
    }
}

    正如源码中提到,它使用ServletRegistrationBean将dispatcherServlet进行注册,并将urlPattern设为了/,这样就类似原来的web.xml中配置的dispatcherServlet。

<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


3、其他Servlet容器

Spring Boot默认支持TomcatJetty,和Undertow作为底层容器。如图:


而Spring Boot默认使用Tomcat,一旦引入spring-boot-starter-web模块,就默认使用Tomcat容器。

切换其他Servlet容器:

1)、将tomcat依赖移除掉

2)、引入其他Servlet容器依赖

引入jetty:

<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>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
引入undertow:
<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>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

切换了Servlet容器后,只是以server开头的配置不一样外,其他都类似。


====================打个广告,欢迎关注====================

QQ:
412425870
微信公众号:Cay课堂

csdn博客:
http://blog.csdn.net/caychen
码云:
https://gitee.com/caychen/
github:
https://github.com/caychen

点击群号或者扫描二维码即可加入QQ群:

328243383(1群)




点击群号或者扫描二维码即可加入QQ群:

180479701(2群)



展开阅读全文

没有更多推荐了,返回首页