以编程方式映射servlet,而不是使用web.xml或注释 [英] Map servlet programmatically instead of using web.xml or annotations
问题描述
如何在没有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>
推荐答案
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.
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); } // ... }
- ServletContainerInitializer与ServletContextListener
- 带有Tomcat 7的@WebServlet注释
- 设计模式"基于Web的应用程序
- 将共享代码和web.xml从WAR项目拆分为通用JAR项目
- 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
您只需确保您的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>
另请参见:
See also:
这篇关于以编程方式映射servlet,而不是使用web.xml或注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!