1. 程式人生 > >SpringBoot內嵌入式的Servlet容器

SpringBoot內嵌入式的Servlet容器

由於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<MyListener> 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);
            }
        };
    }
 
}