1

I want to maintain onw count value over a Http browser. Example :

If browser once open and click on submit button make count as one. again click on button make count as two. and I want count should be less than two.

Consider a count is : private static int count & maxCount is : private int maxCount = 3 code:

 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

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?

Beniton Fernando
  • 1,533
  • 1
  • 14
  • 21
ketan
  • 2,732
  • 11
  • 34
  • 80

1 Answers1

1

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.

Beniton Fernando
  • 1,533
  • 1
  • 14
  • 21
  • It is not the working properly. I want count variable as again zero when I'm hitting URL to the next window of the browser. – ketan Jun 15 '16 at 04:55
  • 1
    @ketan when hitting from next window the count attribute will not be there in the session so you can assume it as zero. – Beniton Fernando Jun 15 '16 at 05:17
  • I tried with that, It's count will be incrementing further when we are hitting url to next window. – ketan Jun 16 '16 at 04:16
  • 1
    Is it next window or tab?. If it is tab then it is not a new session. – Beniton Fernando Jun 16 '16 at 04:18
  • sorry my mistake I mean new tab... If we hit url in the new tab I want count value as a zero then what is the solution for making such a complicated situation as easy...??? – ketan Jun 16 '16 at 05:06
  • @ketan New tab mean it would be in the same session. I will check if there is anyway to find tab info and get back to you on this. – Beniton Fernando Jun 16 '16 at 05:13
  • @ketan May be creating unique id and storing it in sessionStorage should help you. Check this [SO link](http://stackoverflow.com/questions/368653/how-to-differ-sessions-in-browser-tabs) – Beniton Fernando Jun 16 '16 at 05:17