今日份主題‘
Spring Boot整合web基礎組件(Servlet、Filter、Listener)
一般情況下,使用了Spring MVC這些框架後,基本上就不會再去使用Servlet、Filter和Listener這些web組件。但是有時候需要使用第三方的框架,就可能需要使用。比如在使用報表插件的時候,可能就需要使用這些web組件。這也是我們在這裡講解的原因之一。 它們的整合非常簡單,可以在工程中直接定義Servlet、Filter和Listener,不需要使用web.xml,也不需要加任何的依賴。最後就是在啟動類中添加註解@ServletComponentScan。這個註解可以掃描這三種類型的web組件。下面用一個案例來說明。
案例
新建一個工程,在工程中使用web基礎組件,並進行測試。
步驟.01
創建工程chapter04-webcomponent,添加web依賴
02.創建Servlet
@WebServlet(urlPatterns = "/hello_servlet")public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello,Servlet");
}
}
03.創建Filter
@WebFilter
public class HelloFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("hello Filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("hello Filter doFilter");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("hello Filter destroy");
}
}
04.創建Listener
@WebListener
public class HelloHttpSessionListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("HelloHttpSessionListener requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("HelloHttpSessionListener requestInitialized");
}
}
05.在啟動類添加註解@ServletComponentScan
@SpringBootApplication
@ServletComponentScan(basePackages= "com.java.chapter04webcomponent.webcomponent")
public class Chapter04WebcomponentApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter04WebcomponentApplication.class, args);
}
}
06.啟動項目,可以看到如下結果。
大家可以看到過濾器初始化。然後在瀏覽器中輸入:http://localhost:8080/hello_servlet
大家可以看到監聽器、過濾器、servlet都發揮了作用了。
經過峰哥耐心的解說,估計大家對這個問題一定有了全新的認識。大家在平時的學習中如果有類似的疑問,都可以提出來,在後臺留言即可。峰哥看到後,覺得有價值,會以文章的形式專門說明。
閱讀更多 課工場—武漢 的文章