Servlet中的init()方法如何才会在服务器启动时执行

如果要想让 servlet 的 init () 方法在服务器启动 时就被执行,则需要在 web.xml 中相应的 servlet 下配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 6     <display-name></display-name>
 7     <servlet>
 8         <description>This is the description of my J2EE componentHD</description>
 9         <display-name>HellooServlet</display-name>
10         <servlet-name>HelloServlet</servlet-name>
11         <servlet-class>com.yzy.dfd.HelloServlet</servlet-class>
12         <init-param>
13             <param-name>init/param</param-name>
14             <param-value>avalible in servlet init()</param-value>
15         </init-param>
16         <load-on-startup>1</load-on-startup>
17     </servlet>
18 
19     <servlet-mapping>
20         <servlet-name>HelloServlet</servlet-name>
21         <url-pattern>/servlet/HelloServlet</url-pattern>
22     </servlet-mapping>
23     <context-param>
24         <param-name>context/param</param-name>
25         <param-value>avalible during application</param-value>
26     </context-param>
27     <welcome-file-list>
28         <welcome-file>index.jsp</welcome-file>
29     </welcome-file-list>
30 </web-app>

 <load-on-startup>1</load-on-startup>设置为正整数(包括0)

这样此Servlet 就会在服务器启动 时执行了。(注意:如果设置为负整数,则不会在启动 服务器时执行)

如果不配置,启动 服务器时也不会执行,而要等此Servlet 被调用时才会被执行。

 

posted on 2016-08-14 22:59  网络哈气高手  阅读(6115)  评论(0编辑  收藏  举报