SpringBoot-註冊web三大組件
阿新 • • 發佈:2018-11-08
tro ner nts return book hid slist 分享圖片 xtend
創建組件:
Servlet
public class TxServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("hello txjava"); } }View Code
Filter
public class TxFilter implements Filter { @OverrideView Codepublic void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("執行前"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("執行後"); } @Override public void destroy() { } }
Listener
public class TxListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("web容器啟動了"); } @OverrideView Codepublic void contextDestroyed(ServletContextEvent servletContextEvent) { } }
註冊:
@Configuration public class WebConfig { @Bean public ServletRegistrationBean<TxServlet> getTxServlet(){ ServletRegistrationBean<TxServlet> txs = new ServletRegistrationBean<>(new TxServlet()); txs.setUrlMappings(Arrays.asList("/servlet/servlet1")); return txs; } @Bean public FilterRegistrationBean<TxFilter> getFilter(){ FilterRegistrationBean<TxFilter> filter = new FilterRegistrationBean<TxFilter>(); filter.setFilter(new TxFilter()); filter.setUrlPatterns(Arrays.asList("/book/filter")); return filter; } @Bean public ServletListenerRegistrationBean<TxListener> getListener(){ ServletListenerRegistrationBean<TxListener> listener = new ServletListenerRegistrationBean<>(); listener.setListener(new TxListener()); return listener; } }View Code
SpringBoot-註冊web三大組件