真才实料才是最真

Dream have no limit

统计

积分与排名

good link

最新评论

ServletContext and HttpSession

package bean;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;

public class CounterServlet extends HttpServlet {
 
 public static final String CONTENT_TYPE="text/html;charset=GB2312";

 /**
  * Constructor of the object.
  */
 public CounterServlet() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doPost(request,response);

 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

   ServletContext context=getServletContext(); 
   HttpSession   session=request.getSession(true);  
   Integer count=(Integer)context.getAttribute("count");
   Integer count1 = (Integer)session.getAttribute("count1");
   if(count==null){
      count=new Integer(0);
      context.setAttribute("count",new Integer(0));     
     }
   if(count1== null)
   {
    count1=new Integer(0);
    session.setAttribute("count1", new Integer(0));
   }

     response.setContentType(CONTENT_TYPE);

     PrintWriter out=response.getWriter();
     out.println("<HTML>");
     out.println("<HEAD><TITLE>count click times</TITLE></HEAD>");
     out.println("<BODY>");
   
     out.println("<P>Use ServletContext. now click times :"+count+"</P>");  
     out.println("<P>Use HttpSession.    now click times :"+ count1+"</P>"); 
     out.println("</BODY></HTML>");
    
     count=new Integer(count.intValue()+1); 
     count1 = new Integer(count1.intValue()+1);
     context.setAttribute("count",count);
     session.setAttribute("count1", count1);
  
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init(ServletConfig config) throws ServletException {
  
  super.init(config);

  // Put your code here
 }

}

posted on 2007-09-03 15:07 gavinkin555 阅读(537) 评论(0)  编辑 收藏 引用 所属分类: JAVA

只有注册用户登录后才能发表评论。