由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件
public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException { resp.getWriter().println("<h1>hello world</h1>"); }; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } }
public class MyFilter implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("================Hello world Filter"); chain.doFilter(request, response); } }
public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContextListener.super.contextInitialized(sce); System.out.println("-------------MyListener inited !"); } @Override public void contextDestroyed(ServletContextEvent sce) { ServletContextListener.super.contextDestroyed(sce); System.out.println("----------------MyListener Destroy !"); } }
@Configuration public class MyMvcConfig implements WebMvcConfigurer { //注册Servlet @Bean public ServletRegistrationBean<Servlet> myServlet(){ return new ServletRegistrationBean<>(new MyServlet(),"/myServlet"); } //注册Filter @Bean public FilterRegistrationBean<Filter> myFilter(){ FilterRegistrationBean<Filter> filter = new FilterRegistrationBean<>(); filter.setFilter(new MyFilter()); filter.addUrlPatterns("/myServlet"); FilterRegistrationBean<Filter> filter2 = new FilterRegistrationBean<>(new MyFilter(), myServlet()); return filter2; }
//注册Listener @Bean public ServletListenerRegistrationBean<EventListener> myListener(){ ServletListenerRegistrationBean<EventListener> listener = new ServletListenerRegistrationBean<EventListener>(new MyListener()); return listener; } }