【问题标题】:Web.xml configuration replaced with Anotations for LoadOnStartupWeb.xml 配置替换为启动时加载的注释
【发布时间】:2015-05-29 17:28:33
【问题描述】:

规格 Tomcat 8.0.20,操作系统:win 7,Java:1.8

1) Servlet StartServletInit 扩展了 HttpServlet

2) StartServletInit 只有一种方法 "public void init(ServletConfig config)”,它在类路径中读取“属性文件”并打印 在控制台上控制注入的键/值对。

3) Web.xml 有如下标题条目

version="3.1" 
  **metadata-complete="false"**  
  xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
  http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

3) Web.xml 在启动时加载为

<servlet>
<servlet-name>StartServletInit</servlet-name>
<servlet-class>org.web.init.StartServletInit</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

O/p :完美执行并在控制台上打印。 ===> :)

问题

注释 [注释 web.xml 的 loadOnStartup 并注释代码] "@WebServlet(name = "StartServletInit",loadOnStartup = 1)

O/p :不 - 将键/值打印到控制台。 ===> :(

【问题讨论】:

  • 为什么 web.xml 中有双星号?

标签: tomcat annotations servlet-3.0


【解决方案1】:

我认为您不能为同一个 servlet 混合使用 web.xml 配置和注释。您可以使用 web.xml 或注释,但不能同时使用。

尝试从 web.xml 中完全删除 servlet 定义和 servlet 映射,并将 servlet 映射的 url-pattern 的值作为“值”属性放在注解中。使用注解时,servlet 名称并不是很有用。

例子:

@WebServlet(value="/your_url_pattern", loadOnStartup=1)

【讨论】:

    【解决方案2】:

    首先要尝试将 loadOnStartup 设置为 '0',这意味着急切地加载 servlet。

    如果您想在启动时运行代码,最好使用 ServletContextListener。这就是它的用途,而 servlet 大部分时间都在监听请求:

    @WebListener
    public class BootListener implements ServletContextListener {
    
     @Override
     public void contextInitialized(ServletContextEvent sce) {
      // handle app start ...
     }
    
     @Override
     public void contextDestroyed(ServletContextEvent sce) {
      // handle app stop ...
     }
    }
    

    不要混淆注解和 web.xml 声明,使用其中之一。 metadata-complete="false" 将告诉 servlet 容器扫描类路径中的注释。这可能会或可能不会在不同的环境中工作,而 web.xml 中的静态条目将始终有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 2016-02-20
      • 2013-09-30
      • 2019-09-10
      • 1970-01-01
      相关资源
      最近更新 更多