Map servlet programmatically instead of using web.xml or annotations

前端 未结 3 740
春和景丽
春和景丽 2021-01-05 17:26

How can I implement this mapping programmatically without web.xml or annotations? The mission is not to use any framework like spring or something else.

<         


        
3条回答
  •  别那么骄傲
    2021-01-05 18:12

    Since Servlet 3.0 you can use ServletContext#addServlet() for this.

    servletContext.addServlet("hello", test.HelloServlet.class);
    

    Depending on what you're developing, there are two hooks where you can run this code.

    1. If you're developing a publicly reusable modular web fragment JAR file such as existing frameworks like JSF and Spring MVC, then use a ServletContainerInitializer.

      public class YourFrameworkInitializer implements ServletContainerInitializer {
      
          @Override
          public void onStartup(Set> c, ServletContext servletContext) throws ServletException {
              servletContext.addServlet("hello", test.HelloServlet.class);
          }
      
      }
      
    2. Or, if you're using it as an internally integrated part of your WAR application, then use a ServletContextListener.

      @WebListener
      public class YourFrameworkInitializer implements ServletContextListener {
      
          @Override
          public void contextInitialized(ServletContextEvent event) {
              event.getServletContext().addServlet("hello", test.HelloServlet.class);
          }
      
          // ...
      }
      

    You only need to make sure that your web.xml is compatible with Servlet 3.0 or newer (and thus not Servlet 2.5 or older), otherwise the servletcontainer will run in fallback modus complying the declared version and you will lose all Servlet 3.0 features.

    
    
        
    
    

    See also:

    • ServletContainerInitializer vs ServletContextListener
    • @WebServlet annotation with Tomcat 7
    • Design Patterns web based applications
    • Splitting up shared code and web.xml from WAR project to common JAR project

提交回复
热议问题