规范Tomcat 8.0.20,O/s : win 7,Java : 1.8
1) Servlet StartServletInit扩展HttpServlet
2) StartServletInit只有1方法 "public (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 :不-在控制台上打印键/值。===> :( )
发布于 2015-03-25 21:33:05
我不认为您可以为同一个servlet混合web.xml配置和注释。您可以使用web.xml或注释,但不能同时使用。
尝试从web.xml中完全删除servlet定义和servlet映射,并将servlet映射的url-模式的值作为" value“属性放在注释中。在使用注释时,servlet名称并不真正有用。
示例:
@WebServlet(value="/your_url_pattern", loadOnStartup=1)发布于 2015-03-26 07:45:40
首先要尝试的是将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声明混为一谈,请使用它们中的任何一个。元数据-complete=“false”将告诉servlet容器扫描类路径以获得注释。这可能在不同的环境中工作,也可能不起作用,而web.xml中的静态条目总是有效的。
https://stackoverflow.com/questions/29265903
复制相似问题