(see this post)
We used cookies and hashtables to maintain session state.
We can do that easier by using JSP beans.
Using a JSP bean, we leave it to JSP container to create instances of objects and maintain their state (and eventually destroy the object, when appropriate).
Let us create a JSP bean which counts how many times a visitor visits a page within a session.
A JSP Bean is a POJO.
Create a VisitCount.java POJO in your org.confucius folder which looks like this:
package org.confucius;
public class VisitCount {
private int count = 0;
public int getCount() {
count++;
return count;
}
}
It has a single property 'count' which gets updated each time getCount() is called.
Declare this POJO as a JSP Bean in your HelloWorld.jsp and use it to count visits.
Your HelloWorld.jsp will look like this:
<html>
<head>
</head>
<body>
<jsp:useBean id="counter" class="org.confucius.VisitCount" scope="session" />
You have visited <%out.println(counter.getCount());%> times.
</body>
</html>
The jsp:useBean declares a Bean called 'counter', maps it to the VisitCount class, and declares it to be of 'Session' scope.
This means that we want the JSP container to maintain the state of the Bean for the duration of the Session.
The second line calls the getCount() method of the Bean to print out the number of visits.
If you build and deploy HelloWorld.war, and point your browser to:
http://localhost:8080/HelloWorld/jsp/HelloWorld.jsp
you will see the visit count. Each time you refresh the page, the count will increment. The JSP container creates an instance of the Bean and maintains its state for the duration of the session.
If you close your browser, the session ends and the JSP container will destroy the Bean.
If you reopen your browser and revisit the page, the JSP container will create a new instance of the Bean for the new session. You will see that the counter has been reset.
We have used JSP Bean to maintain state. We did not have to maintain cookies and hashtables ourselves.
Nice.
No comments:
Post a Comment