1、编写一个配置类

  1. @Configuration(proxyBeanMethods = true)
  2. public class MyRegistConfig {
  3. @Bean
  4. public ServletRegistrationBean myServlet() {
  5. MyServlet myServlet = new MyServlet();
  6. return new ServletRegistrationBean(myServlet, "/my", "/my2");
  7. }
  8. @Bean
  9. public FilterRegistrationBean myFilter() {
  10. MyFilter myFilter = new MyFilter();
  11. // return new FilterRegistrationBean(myFilter, myServlet());
  12. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
  13. filterRegistrationBean.setUrlPatterns(Arrays.asList("/my", "/css/*"));
  14. return filterRegistrationBean;
  15. }
  16. @Bean
  17. public ServletListenerRegistrationBean myListener() {
  18. MyServletContextListener myServletContextListener = new MyServletContextListener();
  19. return new ServletListenerRegistrationBean(myServletContextListener);
  20. }
  21. }

2、Servlet

不需要加额外注解了,直接编写类本身即可。

  1. public class MyServlet extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. resp.getWriter().write("6666");
  5. }
  6. }

3、Filter

除了 lombok 的 slf4j 用来打印日志以外,不需要加额外注解了,直接编写类本身即可。

  1. @Slf4j
  2. public class MyFilter implements Filter {
  3. @Override
  4. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  5. log.info("MyFilter工作");
  6. chain.doFilter(request, response);
  7. }
  8. @Override
  9. public void init(FilterConfig filterConfig) throws ServletException {
  10. log.info("MyFilter初始化完成");
  11. }
  12. @Override
  13. public void destroy() {
  14. log.info("MyFilter销毁");
  15. }
  16. }

4、Listener

除了 lombok 的 slf4j 用来打印日志以外,不需要加额外注解了,直接编写类本身即可。

  1. @Slf4j
  2. public class MyServletContextListener implements ServletContextListener {
  3. @Override
  4. public void contextInitialized(ServletContextEvent sce) {
  5. log.info("MyServletContextListener 监听到项目初始化完成");
  6. }
  7. @Override
  8. public void contextDestroyed(ServletContextEvent sce) {
  9. log.info("MyServletContextListener 监听到项目销毁");
  10. }
  11. }

测试效果

访问:
http://127.0.0.1/css/bootstrap.min.css
image.png
image.png
可以看到,有在正常工作。

http://127.0.0.1/my
image.png
image.png可以看到有在正常工作。

image.png
Listener 也有正常工作。