java实现页面访问量统计的实例,防刷新

原创
2014/08/19 19:37
阅读数 2.8K

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Count extends HttpServlet
{
         public void doGet(HttpServletRequest request,HttpServletResponse response)
                 throws ServletException,IOException
         {
                 /*//得到当前web应用程序的上下文
                 ServletContext context=this.getServletContext();
                
                 //取出当前保存的属性
                 //如果此页面是第一次被访问,那些count为空,我们帮他初始化为1
                 //如果不是第一次被访问,那么就加1
                 Integer count=(Integer)context.getAttribute("count");
                 if(count==null)
                 {
                         count=new Integer(1);
                 }
                 else
                 {
                         count=new Integer(count.intValue()+1);
                 }*/
             
//             上面的方式是放到了context中,我可以放到session中
             HttpSession session=request.getSession();
             Integer count = (Integer)session.getAttribute("count");
             if(count==null){
                 count = 1;
             }else{
                 
                 if(session.getAttribute("ip")!=null&&!session.getAttribute("ip").equals(getRemortIP(request))){
                     count = new Integer(count.intValue())+1;
                 }
             }
                
                 //设置编码,不然中文会变成乱码
                 response.setContentType("text/html;charset=GB2312");

                 //得到输出流对象
                 PrintWriter out=response.getWriter();
                
                 out.println("<html><head><title>");
                 out.println("页面访问统计");
                 out.println("</title></head><body>");
                 out.println("当前页面被访问了");
                 out.println("<font color=red size=20>"+count+"</font>次");
                 //设置属性,将count保存到当前的上下文中
//                 context.setAttribute("count",count);
                 session.setAttribute("count",count);
                 session.setAttribute("ip",getRemortIP(request));
                 out.close();
         }
         
         /**
          * 获得客户端ip
          * @param request
          * @return
          */
         public String getRemortIP(HttpServletRequest request) {

             if (request.getHeader("x-forwarded-for") == null) {

                 return request.getRemoteAddr();

             }

             return request.getHeader("x-forwarded-for");

        } 

}

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部