以编程方式映射 servlet,而不是使用 web.xml 或注释

Map servlet programmatically instead of using web.xml or annotations

如何在没有 web.xml 或注释的情况下以编程方式实现此映射?任务是不使用任何框架,如 spring 或其他框架。

<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

如果您使用的是 tomcat 7 或更高版本,您可以通过注释

@WebServlet("/hello") 

您可以使用注释通过代码实现这一点。

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        response.getWriter().println("Hello");
    }
}

您可以阅读注释here, here and here

从 Servlet 3.0 开始,您可以使用 ServletContext#addServlet()

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

根据您正在开发的内容,有两个钩子可以让您 运行 此代码。

  1. 如果您正在开发可公开重用的模块化 Web 片段 JAR 文件,例如 JSF 和 Spring MVC 等现有框架,请使用 ServletContainerInitializer.

    public class YourFrameworkInitializer implements ServletContainerInitializer {
    
        @Override
        public void onStartup(Set<Class<?>> c, ServletContext servletContext) throws ServletException {
            servletContext.addServlet("hello", test.HelloServlet.class);
        }
    
    }
    
  2. 或者,如果您将其用作 WAR 应用程序的内部集成部分,则使用 ServletContextListener.

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

你只需要确保你的 web.xml 与 Servlet 3.0 或更新版本兼容(因此不兼容 Servlet 2.5 或更早版本),否则 servletcontainer 将 运行 以符合声明的回退方式版本,您将失去所有 Servlet 3.0 功能。

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0"
>
    <!-- Config here -->
</web-app>

另请参阅:

  • ServletContainerInitializer vs ServletContextListener
  • @WebServlet annotation with Tomcat 7
  • Design Patterns web based applications