1. 程式人生 > >SpringBoot-註冊web三大組件

SpringBoot-註冊web三大組件

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 {
    @Override
    
public 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() { } }
View Code

Listener

技術分享圖片
public class TxListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("web容器啟動了");
    }

    @Override
    
public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
View Code

註冊:

技術分享圖片
@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三大組件