SpringBoot配置嵌入式Servlet容器


SpringBoot默認使用的是Tomcat作為嵌入式的Servlet容器,那么肯定會和外置的Tomcat有區別,那么就這些區別來談一談SpringBoot中對於容器的一些配置操作

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

在內置的Tomcat中,不再有web.xml文件可以供我們修改,那么我們應該怎樣去修改Servlet容器相關的配置呢?在SpringBoot中有兩種方式可供選擇,一種是在配置文件中修改,還有一種是通過配置類的方式去修改

配置文件中修改(具體修改的參數可以查看ServerProperties類)

server.port=8081
server.servlet.context-path=/crud

server.tomcat.uri-encoding=UTF-8

// 通用的Servlet容器設置
server.servlet.xxx
// Tomcat的設置
Server.tomcat.xxx

只需要在application.roperties或者application.yml/yaml中像上面那樣就可以輕松的修改掉相關的配置

編寫配置類(配置方法)

除了像上面那樣在配置文件中修改以外,還可以自己編寫配置類去修改,我們可以編寫一個返回值為EmbeddedServletContainerCustomizer(SpringBoot2.0將其替換成了WebServerFactoryCustomizer)的方法放到我們自定義的配置類中來進行修改,不過在SpringBoot1.x跟SpringBoot2.x版本中有所不同

SpringBoot1.x:

@Bean  //一定要將這個定制器加入到容器中
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
    return new EmbeddedServletContainerCustomizer() {

        //定制嵌入式的Servlet容器相關的規則
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(8083);
        }
    };
}

SpringNoot2.x:

// Servlet容器配置器
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
    return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>(){
        @Override
        public void customize(ConfigurableWebServerFactory factory) {
            factory.setPort(8081);
        }
    };
}

如何注冊Servlet、Filter、Listener三大組件

(1)、ServletRegistrationBean

首先書寫自己的Servlet(要繼承HttpServlet類)

public class MyServlet extends HttpServlet {


    // GET方法
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    // POST方法
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Hello MyServlet");
    }
}
Servlet

將我們自己寫的Servlet注冊

@Bean
public ServletRegistrationBean servletRegistrationBean(){
    /**
     * 第一個參數是我們自己的Servlet對象
     * 第二個參數是是對應的路徑,可以寫多個
     */
    return new ServletRegistrationBean(new MyServlet(), "/servlet");
}
register Servlet

(2)、FilterRegistrationBean

書寫自己的Filter(實現Filter接口)

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("myFilter process...");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
Filter

將我們自己寫的Filter注冊

@Bean
    public FilterRegistrationBean<MyFilter> filterRegistrationBean(){
        FilterRegistrationBean<MyFilter> myFilterFilterRegistrationBean = new FilterRegistrationBean<>();
        myFilterFilterRegistrationBean.setFilter(new MyFilter());
//        myFilterFilterRegistrationBean.addUrlPatterns("/hello", "/myServlet");
        myFilterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
        return myFilterFilterRegistrationBean;
    }
register Filter

(3)、ServletListenerRegistrationBean

定義我們自己的Listener(實現ServletContextListener接口)

public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("web項目啟動了。。。");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("web項目銷毀了。。。");
    }
}
Listener

注冊Listener

@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
    return new ServletListenerRegistrationBean<MyListener> (new MyListener());
}
register Listener

使用注解配置

當然,除了像上面那樣在配置類中注冊我們自定義的三大組件以外,還可以通過注解的方式去配置

首先,在SpringBoot主配置類上標注@ServletComponentScan

想要使用三大組件的注解,就必須先在SpringBoot主配置類(即標注了@SpringBootApplication注解的類)上標注@ServletComponentScan注解

@ServletComponentScan
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

然后就可以開始配置了

配置Servlet

在我們自己的Servlet類上配置 @WebServlet(name = "cus", urlPatterns = "server")  注解即可

配置Filter

在我們自己的Filter上配置 @WebFilter(filterName = "fil", urlPatterns = {"/server", "/hello"}) 注解即可

配置Listener

在我們自己的Listener上配置 @WebListener 即可

以上就是使用注解去配置三大組件

SpringBoot能不能使用其他的Servlet容器

SpringBoot默認使用的是Tomcat,那么能不能切換成其他的容器呢?這個當然是沒問題的,而且切換的方式也很簡單,只需要引入其他容器的依賴,將當前容器的依賴排除即可

切換其他容器

jetty(比較適合做長鏈接的項目,比如聊天等這種一直要連接的)

想要將容器從Tomcat切換到jetty,在pom.xml文件中導入相關依賴即可

<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>
<!-- 引入其他的Servlet容器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

undertow(不支持JSP,但是是一個高性能的非阻塞的Servlet容器,並發性能非常好

引入undertow的方式同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>
<!-- 引入其他的Servlet容器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

只需像上面那樣在pom.xml文件中簡單的引入依賴就可以切換容器了,不再需要做額外的操作

使用外置的Servlet容器

嵌入式的Servlet容器雖然用的挺爽,但是有時候也離不開外置的Servlet容器,首先我們來比較一下嵌入式跟外置的有優缺點

嵌入式Servlet容器:應用打成jar

  • 優點:簡單、便攜
  • 缺點:默認不支持JSP、優化定制比較復雜(使用定制器【ServerProperties、自定義WebServerFactoryCustomizer】,自己編寫嵌入式Servlet容器的創建工廠)

外置的Servlet容器:外面安裝Tomcat,將應用打成war包的方式

外置的Sverlet的缺點也很明顯,那就是使用起來復雜,但是沒有內置的那些缺點,相反這些內置的缺點反而是它的優點

創建項目

首先要創建一個項目,使用war的方式打包

創建webapp文件夾

點擊圖示按鈕

來到Modules下的web

雙擊后會彈出一個框框

我們點擊OK

詢問是否創建webapp,點擊yes即可

創建web.xml

點擊圖示按鈕

點擊web.xml

填寫生成位置

點擊OK然后應用即可

可以看到已經創建完成

之后配置下Tomcat就可以啟動項目了

變化

1、將嵌入式的Tomcat指定為了provided

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

2、編寫了一個類繼承於SpringBootServletInitializer,並重載了configure方法

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
	// 傳入SpringBoot應用的主程序        
	return application.sources(DemoApplication.class);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM