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

Mar*_*ian 4 mapping servlets programmatic-config

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

<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>
Run Code Online (Sandbox Code Playgroud)

ana*_*ron 5

您可以使用注释来使用代码实现此目的.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处,此处此处阅读有关注释的内容


Bal*_*usC 5

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

servletContext.addServlet("hello", test.HelloServlet.class);
Run Code Online (Sandbox Code Playgroud)

根据您正在开发的内容,您可以使用两个钩子来运行此代码.

  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);
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 或者,如果您将其用作WAR应用程序的内部集成部分,则使用a ServletContextListener.

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

您只需要确保您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>
Run Code Online (Sandbox Code Playgroud)

也可以看看: