SpringBoot注册Servlet、Filter、Listener
SpringBoot默认是以jar包的方式启动嵌入式的Servlet容易来启动SpringBoot的Web应用,没有web.xml文件
因此我们可以使用以下方式来注册Servlet、Filter、Listener。
(1)、注册Servlet
1 package cn.coreqi.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 10 public class MyServlet extends HttpServlet { 11 @Override 12 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 13 // 设置响应内容类型 14 resp.setContentType("text/html"); 15 16 // 实际的逻辑是在这里 17 PrintWriter out = resp.getWriter(); 18 out.println("<h1>MyServlet</h1>"); 19 } 20 }
1 //注册Servlet 2 @Bean 3 public ServletRegistrationBean myServlet(){ 4 ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myservlet"); 5 return registrationBean; 6 }
(2)、注册Filter
1 package cn.coreqi.filter; 2 3 import javax.servlet.*; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 7 public class MyFilter implements Filter { 8 @Override 9 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 10 PrintWriter out = servletResponse.getWriter(); 11 out.println("<h1>MyFilter</h1>"); 12 filterChain.doFilter(servletRequest,servletResponse); 13 } 14 }
1 @Bean 2 public FilterRegistrationBean myFilter(){ 3 FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 4 registrationBean.setFilter(new MyFilter()); 5 registrationBean.setUrlPatterns(Arrays.asList("/myservlet")); 6 return registrationBean; 7 }
(3)、注册Listener
1 package cn.coreqi.listener; 2 3 import javax.servlet.ServletContextEvent; 4 import javax.servlet.ServletContextListener; 5 6 public class MyListener implements ServletContextListener { 7 @Override 8 public void contextInitialized(ServletContextEvent sce) { 9 System.out.println("contextInitialized"); 10 } 11 }
1 @Bean 2 public ServletListenerRegistrationBean myListener(){ 3 ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean(); 4 registrationBean.setListener(new MyListener()); 5 return registrationBean; 6 }