spring boot-Servlets, Filters, listeners

3001 ワード

一.Web開発はControllerを用いて基本的に大部分の需要を達成することができるが、サーブレット、Filter、Listenerなどの二.spring bootにおける三つの実現方法の一つ:サーブレットRegistrationBean、FilterRegistrationBean、サーブレットListenerRegistrationBeanを登録することによって制御を得る
/**
*     servlet *
* @author wujing */
public class CustomServlet extends HttpServlet {
/** *
  */
 private static final long serialVersionUID = 1L;
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("servlet get method");
    doPost(request, response);
}
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("servlet post method");
    response.getWriter().write("hello world");
} }
/**
*     filter *
* @author wujing */
public class CustomFilter implements Filter {
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println("init filter");
 }
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    System.out.println("do filter");
    chain.doFilter(request, response);
}
 @Override
 public void destroy() {
    System.out.println("destroy filter");
 }
}
/**
*     listener *
* @author wujing */
public class CustomListener implements ServletContextListener {
 @Override
 public void contextInitialized(ServletContextEvent sce) {
    System.out.println("contextInitialized");
 }
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
    System.out.println("contextDestroyed");
 }
}

登録bean
  @Bean
  public ServletRegistrationBean servletRegistrationBean() {
      return new ServletRegistrationBean(new CustomServlet(), "/roncoo");
  }
  @Bean
  public FilterRegistrationBean filterRegistrationBean() {
     return new FilterRegistrationBean(new CustomFilter(), servletRegistrationBean());
  }
  @Bean
  public ServletListenerRegistrationBean servletListenerRegistrationBean() {
    return new ServletListenerRegistrationBean(new CustomListener()); 
  }

方法2:サーブレットContextInitializerインタフェースの直接登録を実現する
implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
  servletContext.addServlet("customServlet", new CustomServlet()).addMapping("/roncoo");
  servletContext.addFilter("customFilter", new CustomFilter())
.addMappingForServletNames(EnumSet.of(DispatcherType.REQUES T), true, "customServlet");
servletContext.addListener(new CustomListener()); 
}

方法3:SpringBootApplication@ServletComponentScan注釈を使用した後、直接@WebServlet、 @WebFilter、@WebListener注釈によって自動的に登録する