SpringBoot之注册servlet三大组件
1.Servlet
自定义servlet类继承HttpServlet
public class MyServlet 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 {
resp.getWriter().write("hello myservlet");
}
}
使用ServletRegistrationBean
注册servlet
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
return registrationBean;
}
2.Filter
自定义Filter类实现Filter
接口
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("myfilter do do do ... ...");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
使用FilterRegistrationBean
注册filter
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new MyFilter());
filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return filterRegistrationBean;
}
3.Listener
自定义Listener类实现ServletContextListener
接口
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("销毁");
}
}
使用ServletListenerRegistrationBean
注册Listener
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new MyListener());
return servletListenerRegistrationBean;
}