简体   繁体   English

如何在Java中使用HttpSession在浏览器上维护计数值?

[英]how to maintain count value over a Browser using HttpSession in java?

I want to maintain onw count value over a Http browser. 我想通过Http浏览器维护onw计数值。 Example : 范例:

If browser once open and click on submit button make count as one. 如果浏览器一旦打开并单击提交按钮,则将其视为一个。 again click on button make count as two. 再次单击按钮使计数为2。 and I want count should be less than two. 我想计数应该少于两个。

Consider a count is : private static int count & maxCount is : private int maxCount = 3 code: 考虑一个计数为:private static int count和maxCount为:private int maxCount = 3代码:

 protected void processRequest(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {
     HttpSession session = request.getSession();
     session.setAttribute("count", ++count);
     if(session.getAttribute("count") <= maxCount){
         //proccess stuff
     }else{
        //give maxcount completed message
     }
 }

It will work fine when open a browser first time but if I open a browser in another window then it will showing me maxCount completed message 第一次打开浏览器时,它会正常工作,但是如果我在另一个窗口中打开浏览器,它将向我显示maxCount完成的消息

I recognize this count is a static variable and gets memory once and all But what can I do for this. 我知道此计数是一个静态变量,一次又一次获取内存,但是我该怎么办。 I want this count value as again zero when I open in a another window of the browser? 当我在浏览器的另一个窗口中打开时,我希望此计数值再次为零吗?

You can change like this. 您可以像这样更改。

protected void processRequest(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {
     HttpSession session = request.getSession();
     Integer count = (Integer)session.getAttribute("count"); 
     if( count == null) {
         count  = 1;
         session.setAttribute("count", count);   
     }
     if(count <= maxCount){
         session.setAttribute("count", ++count);
         // do other stuff.
     }else{
        //give maxcount completed message
     }
 }

No need to have static variable or even a private variable. 不需要静态变量甚至私有变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM