Servlet在spring boot中怎麼實現的?
- 2019 年 10 月 8 日
- 筆記
傳統的Servlet在spring boot中怎麼實現的?
本文主要內容:
1:springboot一些介紹
2:傳統的servlete項目在spring boot項目中怎麼實現的?web.xml、url-patterns怎麼設置?
3:有幾種實現方式?分別是什麼?
4:程式碼位置
spring boot 三大特性
組件自動裝配:webMVC、webFlux、JDBC等
嵌入式Web容器:Tomcat、Jetty以及undertow
生產準備特性:指標、健康檢查、外部化部署等
組件自動裝配:
激活自動裝配註解:@EnableAutoConfiguration
配置:/META-INF/spring.factories
實現:XXXAutoConfiguration.
我們以spring-boot-autoconfigure的jar下spring.factories為示例:

可以看到key是介面後沒是實現。實現就是XXXAutoConfiguration.
嵌入式web 容器:
Web Servlet容器:Tomcat、Jetty以及undertow
Web Reactive容器:Netty Web Server
生產準備特性:
指標:/actuator/metrices
健康檢查:/actuator/health
外部化配置:/actuator/configprops
Web應用:
傳統的Servlet應用
Servlet組件:Servlet、Filter、listener
Servlet註冊到spring boot中:Servlet註解、Spring Bean、RegistrationBean
非同步非阻塞:非同步Servlet(web 3.0特效)、非阻塞Servlet(servlet 3.1特性)。
來源:凱哥Java(kaigejava)
傳統Servelt應用:
一:添加pom依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二:Servlet組件講解
我們先來回憶下使用Sevlet怎麼寫的:
1:寫個類繼承月HttpServlet。然後重新doGet、doPost方法。如下圖:

2:在web.xml文件中需要配置servlet-name、servlet-calss、servlete-mapping中需要配置url-pattern。如下圖:

然後啟動tomcat之後,在地址欄中輸入xxx:xx/servlet/HelloWorld.
上面是Servlet的步驟。
在spring boot中,提倡使用註解。那麼上面的servlet使用spring boot怎麼使用?
spring boot沒有web.xml怎麼配置?訪問url怎麼配置?
請看下面程式碼:
@WebServlet(urlPatterns = "/servlet/HelloWorld")
public class MyServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("my doGet method");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("my doPost method");
}
}

其中@WebServlet註解和UrlPatterns的功能同web.xml中<servlet-mapping>中的urlpattern.
我們在來看看啟動類上添加:
@SpringBootApplication
@ServletComponentScan("com.kaigejava.web.servlet")
public class Springbootdemo1Application {
public static void main(String[] args) {
SpringApplication.run(Springbootdemo1Application.class, args);
}
}

其中的ServletComponentScan就是掃描servlet的。可以看做是web.xml中<servlet>標籤下的<sevlet-class>。
兩者對比:

啟動項目,訪問:

達到預期效果。說明傳統的servlet在springboot項目中可以很好的兼容。
我們總結下:
SpringBoot中使用傳統的Servlet。
實現方式:
創建一個類添加@WebServlet,繼承HttpServlet,註冊到spring boot容器中。
其中URL映射使用註解:@WebServlet(urlPatterns = "/servlet/HelloWorld")
將servlet註冊到spring容器中使用註解:ServletComponentScan(basePackages=「com.kaigejava.web.servlet」)
我們知道Sevlete還有其他兩個組件:Filter和Listener.
那麼這兩個組件在springboot中又分別使用那些註解呢?
根據servlet註解我們可以看到是@webServlet.
所以,filter對應的就是@WebFilter、listener對應的就是@WebListener註解。
實現方式有三種方式:
第一種:使用servlet註解。如上面我們演示的@Webservlet註解。
其實就是@ServletComponentScan+@webServlet
或者+@WebFilter或者+@WebListener註解
方式二:使用spring註解
@Bean+Servlet(FilterListener)
方式三:使用RegistrationBean方法
ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean
以上三種都可以。
程式碼已發布到git上面。歡迎大家一起學習。