Reputation: 2904
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?
Upvotes: 1
Views: 638
Reputation: 1533
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.
Upvotes: 1