以编程方式映射servlet,而不是使用web.xml或注释 [英] Map servlet programmatically instead of using web.xml or annotations

查看:88
本文介绍了以编程方式映射servlet,而不是使用web.xml或注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

<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>

推荐答案

从Servlet 3.0开始,您可以使用

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. 如果要开发可公共重用的模块化Web片段JAR文件(例如JSF和Spring MVC等现有框架),请使用

  2. 或者,如果您将其用作WAR应用程序的内部集成部分,请使用

  3. 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);
        }
    
        // ...
    }
    

  4. 您只需确保您的web.xml与Servlet 3.0或更高版本兼容(因此与Servlet 2.5或更低版本兼容),否则Servlet容器将以符合声明版本的后备方式运行,并且您将丢失所有Servlet 3.0功能.

    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.

    <?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>
    

    另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆