Now that you've mastered the basics, it's time to bring out thebig iron. This week, The JSP Files explores the various techniquesavailable to "maintain state" on a JSP-based Web site. Learn about theCookie and Session objects, find out how to build a cookie-based hitcounter, and read about a simple yet effective way of protecting sensitiveWeb pages with the Session object.
Here's another simple example which demonstrates some of the methods above,and also illustrates how JSP sessions can be used to protect Web pages withsensitive information.
This example presents a form ("start.html") asking for your name, and takesyou to a new page ("login.jsp") once you submit the form. "login.jsp"creates a session to store the name you entered, and offers a link to"rootshell.jsp", which is the sensitive file to be protected.
So long as the session is active, any attempt to access the page"rootshell.jsp" will succeed. On the flip side, if a session is not active,any attempt to access "rootshell.jsp" by bypassing the initial form willfail, and the user will be redirected to "start.html".
This is a relatively primitive example, but serves to demonstrate one ofthe more common uses of session variables.
All the redirection in this example is accomplished using the Responseobject (you remember this, don't you?)
Once the form is submitted, "login.jsp" takes over.
// get the form variable
String username = request.getParameter("username");
// create a session
// set a timeout period
// display a link to the protected file
out.println("Thank you for using this service.");
out.println("Click <a href=rootshell.jsp>here</a> for root access");
And here's the top-secret page.
// get the username from the session
String username = (String)session.getValue("username");
// if null, security breach!
if (username == null)
// display the protected page
Welcome to your root shell, <b><%= username %></b>!
Your session ID is <% out.println( session.getId() ); %>
This session will expire in <% out.println(
session.getMaxInactiveInterval() ); %> seconds.
To test this, first log in and find your way to "rootshell.jsp" - youshould have no trouble accessing it. Then close the browser, start it upagain, and try to get to "rootshell.jsp" without going through the loginprocess; you should be automatically redirected to the login page.
And that's about it. You should now have a pretty clear idea of how JSPattempts to solve the "stateless protocol" problem, together with someunderstanding of how to create and use both client-side cookies andserver-side sessions. Go practice!