web.xml中
<servlet>
<servlet-name>ServletInit</servlet-name>
<servlet-class>com.rain.init.ServletInit</servlet-class>
<load-on-startup>10</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletInit</servlet-name>
<url-pattern>/ServletInit</url-pattern>
</servlet-mapping>
ServletInit.java中
package com.rain.init;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletInit extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final String CONTENT_TYPE="text/html";
public void init()throws ServletException{
System.out.println("Initing..........");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
ServletContext context=getServletContext();
Integer count=(Integer)context.getAttribute("count");
if(count==null)
{
count=new Integer(0);
context.setAttribute("count",new Integer(0));
}
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head><title>WebCounter</title></head>");
out.println("<body>");
out.println("<p>The current COUNT is:"+count+"</p>");
out.println("</body></html>");
count=new Integer(count.intValue()+1);
context.setAttribute("count", count);
}
public void destroy(){}
}
这样可以实现Servlet的初始化,控制台可以打印出 Initing..........
我希望实现的效果是该初始化类只初始化一些系统信息到内存中,而不执行其他任何操作,对于WEB.XML中的
<load-on-startup>1</load-on-startup> load-on-startup 元素在web应用启动的时候指定了servlet被加载的顺序,它的值必须是一个整数。如果它的值是一个负整数或是这个元素不存在,那么容器会在该servlet被调用的时候,加载这个servlet 。如果值是正整数或零,容器在配置的时候就加载并初始化这个servlet,容器必须保证值小的先被加载。如果值相等,容器可以自动选择先加载谁。
觉得这样是不是不大必要,是否可以直接用<init></init>如何实现的啊,指点哈
<servlet>
<servlet-name>ServletInit</servlet-name>
<servlet-class>com.rain.init.ServletInit</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
以下可以没有
<servlet-mapping>
<servlet-name>ServletInit</servlet-name>
<url-pattern>/ServletInit</url-pattern>
</servlet-mapping>