When you do visits = visits + 1
, you're assigning a new object to the visits reference, and the session keeps pointing at the older value:
Before getting the attribute:
session ---> Integer(1)
After getting the attribute:
session ---> Integer(1)
^
visits ---------|
After visits = visits + 1
session ---> Integer(1)
visits ----> Integer(2)
You wouldn't need to set the attribute again in the session is you used a mutable counter object, and did the following:
Counter counter = (Counter) session.getAttribute("visits");
counter.increment();
Where increment()
would do:
this.value++;
Java has such a class: AtomicInteger:
AtomicInteger counter = session.getAttribute("visits");
counter.incrementAndGet();