Spring Boot 學習系列(08)—自定義servlet、filter及listener
此文已由作者易國強授權網易雲社群釋出。
歡迎訪問網易雲社群,瞭解更多網易技術產品運營經驗。
傳統的filter及listener配置
在傳統的Java web專案中,servlet、filter和listener的配置很簡單,直接在web.xml中按順序配置好即可,程式啟動時,就會按照你配置的順序依次載入(當然,web.xml中各配置資訊總的載入順序是context-param -> listener -> filter -> servlet),專案搭建完成後,估計一般新來的開發同學沒啥事都不會去關注裡面都做了些啥~ = =
廢話少說,上程式碼,下面是一個傳統的web.xml配置示例。
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- define charset --><filter> <filter-name>Set UTF-8</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param></filter><servlet> <servlet-name>silver</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:xxx-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>silver</servlet-name> <url-pattern>/</url-pattern></servlet-mapping>
Spring Boot中該如何配置?
需要說明的是,Spring Boot專案裡面是沒有web.xml的,那麼listener和filter我們該如何配置呢?
在Spring Boot專案中有兩種方式進行配置,一種是通過Servlet3.0+提供的註解進行配置,分別為@WebServlet、@WebListener、@WebFilter。示例如下:
import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException;/** * @author bjyiguoqiang * @date 2017/11/9 17:28. */@WebFilter(urlPatterns = "/*", filterName = "helloFilter")public class HelloFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init helloFilter"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("doFilter helloFilter"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author bjyiguoqiang * @date 2017/11/9 17:27. */@WebServlet(name = "hello",urlPatterns = "/hello")public class HelloServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("hello word"); resp.getWriter().flush(); resp.getWriter().close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;/** * @author bjyiguoqiang * @date 2017/11/9 17:28. */@WebListenerpublic class HelloListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("HelloListener contextInitialized"); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
最後在程式入口類加入掃描註解@ServletComponentScan即可生效。
@[email protected] class DemoaApplication { public static void main(String[] args) { SpringApplication.run(DemoaApplication.class, args); } }
需要注意的是,使用@WebFilter 是無法實現filter的過濾順序的,使用org.springframework.core.annotation包中的@Order註解在spring boot環境中也是不支援的。所有如果需要對自定義的filter排序,那麼可以採用下面所述的方式。
另一種配置則是通過Spring Boot提供的三種類似Bean實現的,分別為ServletRegistrationBean、ServletListenerRegistrationBean以及FilterRegistrationBean。使用示例分別如下:
import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author bjyiguoqiang * @date 2017/11/9 17:44. */@Configurationpublic class MyConfigs { /** * 配置hello過濾器 */ @Bean public FilterRegistrationBean sessionFilterRegistration() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new HelloFilter()); registrationBean.addUrlPatterns("/*"); registrationBean.addInitParameter("session_filter_key", "session_filter_value"); registrationBean.setName("helloFilter"); //設定載入順序,數字越小,順序越靠前,建議最小從0開始配置,最大為Integer.MAX_VALUE registrationBean.setOrder(10); return registrationBean; } /** * 配置hello Servlet */ @Bean public ServletRegistrationBean helloServletRegistration() { ServletRegistrationBean registration = new ServletRegistrationBean(new HelloServlet()); registration.addUrlMappings("/hello"); //設定載入順序,數字越小,順序越靠前,建議最小從0開始配置,最大為Integer.MAX_VALUE registration.setOrder(3); return registration; } /** * 配置hello Listner */ @Bean public ServletListenerRegistrationBean helloListenerRegistrationBean(){ ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean(); servletListenerRegistrationBean.setListener(new HelloListener()); //設定載入順序,數字越小,順序越靠前,建議最小從0開始配置,最大為Integer.MAX_VALUE servletListenerRegistrationBean.setOrder(3); return servletListenerRegistrationBean; } }
通過Bean注入的方式進行配置,可以自定義載入順序,這點很nice。
最後
在Spring Boot的環境中配置servlet、filter和listener雖然沒有在web.xml中配置那麼直觀,不過也是挺簡單的。
不足之處,歡迎指正,謝謝~
更多網易技術、產品、運營經驗分享請點選。
相關文章:
【推薦】 大資料、資料探勘在交通領域的應用
【推薦】 微服務實踐沙龍-上海站
【推薦】 掃臉動畫