一、自定义原生Servlet
1、启动类里面增加注解 @ServletComponentScan
2、Servlet上添加注解 @WebServlet(name = "userServlet",urlPatterns = "/v1/api/test/customs")
1 @WebServlet(name = "userServlet",urlPatterns = "/v1/api/test/customs") 2 public class UserServlet extends HttpServlet{ 3 4 @Override 5 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 6 7 resp.getWriter().print("custom sevlet"); 8 resp.getWriter().flush(); 9 resp.getWriter().close(); 10 } 11 12 @Override 13 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 14 throws ServletException, IOException { 15 this.doGet(req, resp); 16 } 17 18 }
二、自定义原生Listener
常用的监听器 servletContextListener、httpSessionListener、servletRequestListener
servletContextListener:服务启动,一般用于初始化加载
servletRequestListener:访问启动,一般用于统计
1 @WebListener 2 public class CustomContextListner implements ServletContextListener{ 3 4 @Override 5 public void contextInitialized(ServletContextEvent sce) { 6 System.out.println("======contextInitialized========"); 7 //启动时触发 8 } 9 10 @Override 11 public void contextDestroyed(ServletContextEvent sce) { 12 System.out.println("======contextDestroyed========"); 13 14 } 15 16 }
1 @WebListener 2 public class RequestListener implements ServletRequestListener { 3 4 @Override 5 public void requestDestroyed(ServletRequestEvent sre) { 6 // TODO Auto-generated method stub 7 System.out.println("======requestDestroyed========"); 8 } 9 10 @Override 11 public void requestInitialized(ServletRequestEvent sre) { 12 System.out.println("======requestInitialized========"); 13 14 } 15 16 }