P137实验题:修改(Tomcat与JavaEE开发技术详解(第三版))本章4.4.1节的例程4-9的CounterServlet类,并修改web.xml文件中对CounterServlet类的配置,使它能完成与4.4.2节的例程4-11的MyServletContextListener相似的功能。修改后的CounterServlet增加了以下功能:
(1)当Servlet容器启动Web应用时,就会初始化CounterServlet。
(2)当Servlet容器初始化CountServlet时,CounterServlet读取count/count.txt文件中计数器的初始值,然后创建一个具有该功能的Counter对象,把它存放在Web应用范围内。
(3)当Servlet容器销毁CounterServlet时,CounterServlet把Web应用范围内的Counter对象的计数值保存到count/count.txt文件中。
Codes:
package mypack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class CounterServlet1 extends HttpServlet implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
System.out.println("(CounterServlet1)helloapp2 application is Initialized.");
//获取ServletContext对象
ServletContext context = sce.getServletContext();
try {
//从文件中读取计数器的数值
BufferedReader reader=new BufferedReader(
new InputStreamReader(context.getResourceAsStream(
"/count/count.txt")));
int count=Integer.parseInt(reader.readLine());
reader.close();
System.out.println("(CounterServlet1)count="+count);
//创建计数器对象
Counter counter=new Counter(count);
//把计数器对象保存到Web应用范围
context.setAttribute("counter", counter);
}catch(Exception e) {
System.out.println("errorMode:"+e.getMessage());
}
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("(CounterServlet1)helloapp2 application is Destroyed.");
//获取ServletContext对象
ServletContext context=sce.getServletContext();
//从Web应用范围获得计数器对象
Counter counter=(Counter)context.getAttribute("counter");
if(counter!=null) {
try {
//把计数器的数值写到context.txt文件中
String filepath=context.getRealPath("/count");
filepath=filepath+"/count.txt";
PrintWriter pw=new PrintWriter(filepath);
pw.println(counter.getCount());
System.out.println("(CounterServlet1)count="+counter.getCount());
pw.close();
}catch(Exception e){
System.out.println("errorMode:"+e.getMessage());
}
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException {
//获得ServletContext的引用
ServletContext context=getServletContext();
//从ServletContext中读取 counter属性
Counter counter=(Counter)context.getAttribute("counter");
//如果ServletContext中没有counter属性,就创建counter属性
if(counter==null) {
counter=new Counter(1);
context.setAttribute("counter", counter);
}
response.setContentType("text/html;charset=GBK");
PrintWriter out=response.getWriter();
out.println("<html><head><title>CounterServlet</title></head?");
out.println("<body>");
//输入当前的counter属性
out.println("<h1>Welcome to our web-page.You're the "+counter.getCount()+" th visiter!</h1>");
out.println("</body></html>");
counter.add(1); //将计数器 增 1
out.close();
}
}