傳統的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)
www.kaigejava.com
傳統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(Filter\Listener)
方式三:使用RegistrationBean方法
ServletRegistrationBean
FilterRegistrationBean
ServletListenerRegistrationBean
以上三種都可以。
代碼已發布到git上面。歡迎大家一起學習。
