如何在没有 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>
从 Servlet 3.0 开始,您可以使用ServletContext#addServlet()为了这。
servletContext.addServlet("hello", test.HelloServlet.class);
根据您正在开发的内容,您可以通过两个挂钩来运行此代码。
-
如果您正在开发可公开重用的模块化 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);
}
}
-
或者,如果您将其用作 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 或更早版本),否则 servlet 容器将以符合声明版本的后备模式运行,并且您将失去所有 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 与 ServletContextListener
- Tomcat 7 的 @WebServlet 注释
- 基于网络的应用程序设计模式
- 将共享代码和 web.xml 从 WAR 项目拆分为公共 JAR 项目
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)