01 | package com.chen.servlet; |
03 | import java.io.IOException; |
04 | import java.io.PrintWriter; |
05 | import javax.servlet.ServletContext; |
06 | import javax.servlet.ServletException; |
07 | import javax.servlet.http.HttpServlet; |
08 | import javax.servlet.http.HttpServletRequest; |
09 | import javax.servlet.http.HttpServletResponse; |
11 | public class CounterServlet extends HttpServlet { |
16 | private static final long serialVersionUID = 1L; |
19 | * 在程序代码中33行,调用getServletContext()方法(从GenericServlet类间接继承而来)得到Web应用程序的上下文对象 |
20 | * 。为了避免线程安全的问题,我们在第35行使用synchronized关键字对context对象进行同步。第36行, |
21 | * 调用上下文对象的getAttribute()方法获取counter属性的值。第36~40行,判断count是否为null,如果为null,则将它的初始值设为1 |
22 | * 。当这个Servlet第一次被访问的时候 ,在上下文对象中还没有保存counter属性,所以获取该属性的值将返回null。如果count不为null, |
23 | * 则将count加1。第40行,将count作为counter属性的值保存到ServletContext对象中 |
24 | * 。当下一次访问这个Servlet时,调用getAttribute()方法取出counter属性的值不为null, |
25 | * 于是执行第38行的代码,将count加1,此时count为2,表明页面被访问了两次。 |
26 | * 第49行,输出count,显示该页面的访问次数 |
28 | public void doGet(HttpServletRequest req, HttpServletResponse resp) |
29 | throws ServletException, IOException { |
31 | ServletContext context = getServletContext(); |
33 | synchronized (context) { |
34 | count = (Integer) context.getAttribute( "counter" ); |
36 | count = new Integer( 1 ); |
38 | count = new Integer(count.intValue() + 1 ); |
40 | context.setAttribute( "counter" , count); |
43 | resp.setContentType( "text/html;charset=gb2312" ); |
44 | PrintWriter out = resp.getWriter(); |
46 | out.println( "<html><head>" ); |
47 | out.println( "<title>页面访问统计</title>" ); |
48 | out.println( "</head><body>" ); |
49 | out.println( "该页面已被访问了" + "<b>" + count + "</b>" + "次" ); |
50 | out.println( "</body></html>" ); |