A session is a period of activity on a specific site. A session begins when a user makes their first request for a page but the end of a session is a little more complicated. Since there is no way of knowing whether a user is going to request another page it is not possible to end a session when a user makes their last request. Instead a session ends after a fixed period after the user’s last request. There are several different ways of tracking a user’s session.
- The user logs in with a username and password.
- Hidden Forms.
- URL Rewriting.
- Persistent Cookies.
Session portion of the Servlet API
Using the Session Tracking API it is possible to manage session tracking without explicitly using the following alternative methods:
* User logs in with a username and password
* Hidden Fields in Forms
* Rewriting URLs
* Persistent Cookies.
The Session API is part of the Servlet API. It provides us with inbuilt session tracking. Behind the scenes Persistent Cookies are used but you do not have to deal with Cookies yourself. Some Servlet Engines can build on the basic functionality provided by the Session API and can transparently revert to techniques such as URL Rewriting if cookies fail.
HttpSession
Every user is associated with a javax.servlet.http.HttpSession
object that servlets can use to store or retrieve information about that user.getSession()
method from the HttpServletRequest object is used by a servlet to get the current HTTPSession object.public HttpSession HttpServletRequest.getSession(boolean create)
If create is set to true a new session is created for the user if they do not have a session already. If create is set to false the method will return null if the user does not have a session already.
Example 1:
Hit Counter
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class PageCountUsingSessionAPI extends HttpServlet {
public void doRetrieve(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintShopper aPS = response.getWriter();
//Retrieve session object. If it does not exist yet, create one.
HttpSession aHttpSession = request.getSession(true);
aPS.println("<HTML><HEAD><TITLE>Using Session API"+
"</TITLE></HEAD><BODY>");
this.incrementNumHitsThisPage(aHttpSession);
int hits = this.showNumHitsThisPage(aHttpSession);
aPS.println("Number times you have visited this page: " + hits);
aPS.println("</BODY></HTML>");
}
private static synchronized int showNumHitsThisPage(
HttpSession aHttpSession) {
// Get the object in the user' session called
// "NumHits.ShowSessionDataPage"
Integer count = (Integer)aHttpSession.getAttribute
("NumHits.ShowSessionDataPage");
return count.intValue();
}
private static synchronized void incrementNumHitsThisPage(
HttpSession aHttpSession)
{Integer count = (Integer)aHttpSession.getAttribute
("NumHits.ShowSessionDataPage");
if (count == null) {
count = new Integer(1);
}else {
// increment counter
count = new Integer(count.intValue() + 1);
}
aHttpSession.setAttribute
("NumHits.ShowSessionDataPage", count);
}
}
Example 2:
We are now going to create a Servlet that allows you to add and view objects that are stored in a user’s HttpSession. The Servlet can display different pages depending on the value of a parameter called “command” passed to it. The Servlet can display a page for entering data to the HttpSession or a page to show all the objects currently stored in the HttpSession. In addition it shows cookie data. The Session API(Part of the Servlet API) uses cookies behind the scenes. To use the Session API however you do not need to deal with the cookies directly yourself.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class SaveSessionData extends HttpServlet {
public void doRetrieve(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintShopper aPS = response.getWriter();
aPS.println("<HTML><HEAD><TITLE>Using Session API"+
"</TITLE></HEAD><BODY>");
// Get the current session object.
//If it does not exist yet create one.
HttpSession aHttpSession = request.getSession(true);
// This servlet could have been separated out into
several different servlets.
// Instead a parameter called "command" allows us to
keep the code in one
// servlet. The parameter's value determines how the
Servlet reacts to
// a request. If the value is null the servlet will bring up the default
// page showing session data.
String command = (String)request.getParameter("command");
System.out.println("command = " + command);
if (command != null) {
if (command.equals("Add Data")) {
// Page where the user can enter data to store in the HttpSession saveToSession(aPS);
}else if (command.equals("Delete All Data")) {
// deletes each object stored in the HttpSession deleteSessionData(aHttpSession);
// display Session Data
showSessionData(aPS , request, aHttpSession);
}else if (command.equals("Save")) {
// display Session Data
showSessionData(aPS , request, aHttpSession);
}
}else {
// display default page: Session Data
showSessionData(aPS , request, aHttpSession);
}
aPS.println("</BODY></HTML>");
}
// The Servlet Session API uses cookies behind the scenes.
// This method
// lets you see the cookies
private static synchronized void showCookies(
HttpServletRequest request,
PrintShopper aPS) {
Cookie cookie[] = request.getCookies();
aPS.println("<TABLE CELLSPACING='1' CELLPADDING='1'>");
for (int j=0; j<cookie.length; j++) {
aPS.println("<TR><TD><B>Name</B></TD><TD> = <B>" +
cookie[j].getName() + 1."</B></TD></TR>");
aPS.println("<TR><TD>Value</TD><TD> = " + cookie[j].getValue() + 1. "</TD></TR>");
aPS.println("<TR><TD>Version</TD><TD> = " +cookie[j].getVersion() + 1. "</TD></TR>");
aPS.println("<TR><TD>Path</TD><TD> = " +
cookie[j].getPath() + 1. "</TD></TR>");
aPS.println("<TR><TD>Domain</TD><TD> = " +
cookie[j].getDomain() + 1. "</TD></TR>");
aPS.println("<TR><TD>Comment</TD><TD> = " + cookie[j].getComment() + 1. "</TD></TR>");
aPS.println("<TR><TD>Max Age</TD><TD> = " +cookie[j].getMaxAge() + 1. "</TD></TR>");
aPS.println("<TR><TD>Secure</TD><TD> = " + cookie[j].getSecure() + "</TD></TR>");
aPS.println("<TR><TD COLLSPAN=2> </TD></TR>");
}
aPS.println("</TABLE>");
}
// Each object stored in the HttpSession is removed
private static synchronized void deleteSessionData
(HttpSession aHttpSession) {
Enumeration enumNames = aHttpSession.getAttributeNames();
String name;
while (enumNames.hasMoreElements()) {
name = (String)enumNames.nextElement();
// remove object from HttpSession
aHttpSession.removeAttribute(name);
}
}
// Creates a web page that you can enter data to store in
the HttpSession
private static synchronized void saveToSession
(PrintShopper aPS) {
// displays 2 boxes that you can enter the key and value
of the data you
// want to store in the HttpSession
aPS.println(<FORM ACTION='SaveSessionData' METHOD=GET>");
aPS.println(<H1><B>Saving Session Data</B></H1><BR>");
aPS.println("<TABLE>");
aPS.println("<TR><TD>Enter Key:</TD>");
aPS.println("<TD><INPUT TYPE='Text' NAME='key'"+
" ALIGN='left' SIZE='30'></TD></TR>");
aPS.println("<TR><TD>Enter Data:</TD>");
aPS.println("<TD><INPUT TYPE='Text' NAME='data'"+
" ALIGN='left' SIZE='30'></TD></TR>");
aPS.println("<TR><TD COLSPAN='2'><INPUT "+
"TYPE='submit' NAME='command' VALUE='Save'>");
aPS.println("</TD></TR></TABLE></FORM>");
}
// Shows Session Data from the HttpSession and cookies
private static synchronized void showSessionData(
PrintShopper aPS,
HttpServletRequest request,
HttpSession aHttpSession) {
// The creation and access times for the session are
// expressed
// as number of seconds since January 1, 1970,
// 00:00:00 GMT
// Here we convert the seconds into Date
Date aDateCreationTime = new Date(
aHttpSession.getCreationTime());
Date aDateLastAccessed = new Date(
aHttpSession.getLastAccessedTime());
// Reads in data that you wish to add to the HttpSession
String key = request.getParameter("key");
String data = request.getParameter("data");
if (key != null && data != null) {
// if data we wish to store was passed in add
it to the HttpSession
aHttpSession.setAttribute(key, data);
}
// Print out Session ID and creation and access times
aPS.println("<FORM ACTION='SaveSessionData' METHOD=GET>");
aPS.println("<H1><B>Showing Session Data</B></H1>");
aPS.println("<BR>");
aPS.println("<TABLE>");
aPS.println("<TR><TD>Your Session ID :</TD><TD>");
aPS.println(aHttpSession.getId().trim() + "</TD></TR>");
aPS.println("<TR><TD>Session Creation Time :</TD><TD>");
aPS.println(aDateCreationTime.toString() + "</TD></TR>");
aPS.println("<TR><TD>Session Last Accessed :</TD><TD>");
aPS.println(aDateLastAccessed.toString() + "</TD></TR>");
aPS.println("</TABLE>");
aPS.println("<BR><BR>");
aPS.println("<B>Cookies:</B><BR>");
showCookies(request, aPS);
aPS.println("<BR><BR>");
aPS.println("<B>Session objects stored: </B><BR><BR>");
aPS.println("<TABLE BORDER='1' CELLPADDING='5'"+
" CELLSPACING='5'>");
aPS.println("<TR BGCOLOR='antiquewhite'>");
aPS.println("<TD>Name</TD><TD>Value</TD>");
aPS.println("</TR>");
// Get all the names of objects stored in the HttpSession
// For each name get the corresponding object and print it out.
Enumeration enumNames = aHttpSession.getAttributeNames();
Object aObject;
while (enumNames.hasMoreElements()) {
key = (String)enumNames.nextElement();
aObject = aHttpSession.getAttribute(key);
aPS.println("<TR><TD>" + key + "</TD><TD>" +
aObject + "</TD></TR>");
}
aPS.println("</TABLE>");
// Takes you to a page where you can enter more data to store in the //HttpSession
aPS.println("<BR><INPUT TYPE='submit' NAME='command'"+
" VALUE='Add Data'>");
// Deletes all objects stored in the HttpSession and
// then creates a page where
// you can see Session Data and Cookies
aPS.println("<INPUT TYPE='submit' NAME='command' "+"VALUE='Delete All Data'></FORM>");
}
}
Example 3:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class OnlineStoreCartSessionTracking extends HttpServlet {
public void doRetrieve(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintShopper aPS = response.getWriter();
aPS.println("<HTML><HEAD><TITLE>"+
"Session Tracking API OnlineStore Basket" +
"</TITLE></HEAD><BODY>");
String actionString = request.getParameter("submit");
if (actionString != null) {
if (actionString.equals("Add More goods")) {
System.out.println("addToOnlineStoreCart");
addToOnlineStoreCart(request, aPS);
}else if (actionString.equals("Review OnlineStore Cart")) {
reviewOnlineStoreCart(request, aPS);
System.out.println("reviewOnlineStoreCart");
}
}else {
reviewOnlineStoreCart(request, aPS);
}
aPS.println("</FORM></BODY></HTML>");
}
private static synchronized void addToOnlineStoreCart
(HttpServletRequest request,
PrintShopper aPS) {
aPS.println("<FORM ACTION="+
"'OnlineStoreCartSessionTracking' METHOD=GET>");
aPS.println("Add to Basket:<BR><BR>");
aPS.println("<INPUT TYPE='checkbox' NAME='goods' "+
"VALUE='Pencils $2.0'>Pencils $2<BR>");
aPS.println("<INPUT TYPE='checkbox' NAME='goods'"+
" VALUE='Rubbers $30.0'>Rubbers $30<BR>");
aPS.println("<BR><BR><INPUT TYPE='Submit' "+
"NAME='submit' VALUE='Review OnlineStore Cart'>");
}
private static synchronized void reviewOnlineStoreCart(
HttpServletRequest request,
PrintShopper aPS) {
// get current session object. If there is not one create
// one
HttpSession aHttpSession = request.getSession(true);
// look for vector of goods in HttpSession
Vector goodsVec = (Vector)aHttpSession.getAttribute
("cart.goods");
if (goodsVec == null) {
// if the vector of goods is not in the HttpSession
// create a new Vector
aHttpSession.setAttribute("cart.goods", new Vector());
goodsVec = (Vector)aHttpSession.getAttribute("cart.goods");
}
// read in the new goods the user wishs to add to their
OnlineStore cart
String newgoods[] = request.getParameterValues("goods");
// if there are new goods to add to the OnlineStore cart add
them to the goodsVec
if (newgoods != null) {
System.out.println("newgoods.length = " +
newgoods.length);
for (int j=0; j<newgoods.length; j++) {
goodsVec.addElement(newgoods[j]);
}
// update HttpSession.
aHttpSession.setAttribute("cart.goods", goodsVec);
}
aPS.println("Review OnlineStore Basket<BR><BR>");
if (goodsVec.size() > 0) {
Enumeration aEnumgoods = goodsVec.elements();
float count = 0;
aPS.println("<UL>");
while (aEnumgoods.hasMoreElements()) {
String details = (String)aEnumgoods.nextElement();
int positionOfPound = details.indexOf("$") + 1;
String numberStr = details.substring(positionOfPound);
float price = Float.parseFloat(numberStr);
count = count + price;
aPS.println("<LI>" + details);
}
aPS.println("<BR><BR>Total: $" + count);
aPS.println("</UL>");
}else {
aPS.println("There are no goods in basket");
}
aPS.println("<FORM ACTION='OnlineStoreCartSessionTracking'"+
" METHOD=GET>");
aPS.println("<BR><BR><INPUT TYPE='Submit' NAME='submit'"+" VALUE='Add goods'>");
}
}
Persistent Cookies
A cookie is an information bit sent by a web server to a browser that can later be read back from that browser. As cookies have the capability to identify a client, they are often used for tracking sesions. The Servlet API gives the javax.servlet.http.Cookie class that works with Cookies.
HttpServletResponse has the following method:public void addCookie(Cookie aCookie)
The Cookie’s constructor is: public Cookie(String name, String Value)
e.g. Cookie aCookie = new Cookie(“ID”, “178”);
HttpServletRequest has the following method:public Cookie[] getCookies()
. getCookies()
returns an array of cookies.
The first time a request is made to OnlineStoreCartCookies.java, the servlet checks whether a cookie called “sessionID” was sent from the users browser. If there is no such sessionID, a new Cookie is created and sent to the browser. A hashtable stores OnlineStore basket information using the sessionID as the key.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class OnlineStoreCartCookies extends HttpServlet {
// Hashtable is static so that all threads running
OnlineStoreCartURLRewrite access
// the same Hashtable. The hashtable key is a unique sessionID.
// stored is a vector of goods the user has added to their
//OnlineStore Cart.
public static Hashtable aHashtable;
// Hashtable is initialised when Servlet Thread started
public void init() {
aHashtable = new Hashtable();
}
// This creates a unique sessionID
private static synchronized long milliSecondsSince1970() {
Date aDate = new Date();
long numberMilliSecondsSince1970 = aDate.getTime();
try {
Thread.sleep(1);
}catch (InterruptedException e){}
return numberMilliSecondsSince1970;
}
public void doRetrieve (HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintShopper aPS = response.getWriter();
String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int j=0; j<cookies.length; j++) {
if (cookies[j].getName().equals("sessionID")) {
sessionID = cookies[j].getValue();
break;
}
}
}
if (sessionID == null) {
sessionID = "" + milliSecondsSince1970();
// Creates a new Cookie called "sessionID" because
it does not exist yet.
Cookie aCookie = new Cookie("sessionID", sessionID);
response.addCookie(aCookie);
// add an empty vector to the hashtable using the
sessionID as the key.
// The vector will be used for storing OnlineStore
cart goods
aHashtable.put(sessionID, new Vector());
}
aPS.println("<HTML><HEAD><TITLE>OnlineStore Cart using"+" Cookies</TITLE></HEAD></HTML>");
aPS.println("<BODY>");
String actionString = request.getParameter("submit");
if (actionString != null) {
if (actionString.equals("Add More goods")) {
System.out.println("addToOnlineStoreCart");
addToOnlineStoreCart(sessionID, aPS);
}
else if (actionString.equals("Review OnlineStore Cart"))
{
System.out.println("reviewOnlineStoreCart");
reviewOnlineStoreCart(request, sessionID, aPS);
}
}else {
reviewOnlineStoreCart(request, sessionID, aPS);
}
aPS.println("</FORM></BODY></HTML>");
}
private static synchronized void addToOnlineStoreCart(
String sessionID, PrintShopper aPS) {
aPS.println("<FORM ACTION='http://localhost:8080"+
"/jack/servlet/OnlineStoreCartCookies'
METHOD=GET>");
aPS.println("Add to Basket:<BR><BR>");
aPS.println("<INPUT TYPE='checkbox' NAME='goods'"+
" VALUE='Pencils $2.0'>Pencils $2<BR>");
aPS.println("<INPUT TYPE='checkbox' NAME='goods'"+
" VALUE='Rubbers $30.0'>Rubbers $30<BR>");
aPS.println("<BR><BR><INPUT TYPE='Submit' NAME='submit'"
+"VALUE='Review OnlineStore Cart'>");
}
private static synchronized void reviewOnlineStoreCart(
HttpServletRequest request,
String sessionID,
PrintShopper aPS) {
// get new goods
String goods[] = request.getParameterValues("goods");
// get the vector of goods from the hashtable using the
// sessionID as key
Vector goodsVec = Vector)aHashtable.get(sessionID);
if (goods != null) {
for (int j=0; j < goods.length; j++) {
// adds the new goods the user added to his OnlineStore Cart
goodsVec.addElement(goods[j]);
}
}
if (goodsVec.size() == 0) {
aPS.println("No goods in basket yet");
}else {
Enumeration aEnum = goodsVec.elements();
float count = 0;
aPS.println("<UL>");
while (aEnum.hasMoreElements()) {
String details = (String)aEnum.nextElement();
int positionOfPound = details.indexOf("$") + 1;
String numberStr = details.substring
(positionOfPound);
float price = Float.parseFloat(numberStr);
count = count + price;
aPS.println("<LI>" + details);
}
aPS.println("<BR><BR>Total: $" + count);
aPS.println("</UL>");
}
aPS.println("<FORM ACTION='http://localhost:8080/"+
"jack/servlet/OnlineStoreCartCookies' METHOD=GET>");
aPS.println("<BR><BR><INPUT TYPE='Submit' NAME='submit'"+
" VALUE='Add More goods'>");
}
}
Rewriting URLs
The idea of this method of session tracking is to assign a unique ID to a user when they first log on. This ID is then passed in the URL of links while the user navigates around the site.
For example, the following URL has the sessionID number tagged on as a path at the end of the URL before the parameters: http://localhost:8080/jack/servlet/OnlineStoreCartURLRewrite/988383098062?submit=Add+More+goods
In the above example 988383098062 is the sessionID.
Consider a OnlineStore Basket example. The first time a user makes a request for the OnlineStoreCartURLRewrite.java servlet they are assigned a unique sessionID. This unique sessionID is used as the Key in a static hashtable to store OnlineStore information relating to a user. The hashtable is static which means that if the tomcat servlet engine creates a new thread running the servlet, all threads will be accessing the same hashtable.
When a user requests a web page from the servlet a web page is dynamically created. All links in the pages to servlets have the user’s sessionID inserted into the URL.
All methods called by doRetrieve()
or doPost()
are synchronized to prevent request calls interfering with each other.
This makes it possible to check in the code connected to the Get method, which user made the request. (See methods reviewOnlineStoreCart()
and AddToOnlineStoreCart()
).
By storing information in a hashtable (using the user’s sessionID as a unique Key ) we are able to keep track of information between requests to the Servlet.
Hidden Forms
When a servlet receives a request, information may be passed to it by:
* The URL Get method
* The Post method
If the servlet wants to have access to this information later on when the user makes another request(session tracking) it can be achieved as follows:
The information passed to the servlet is written back in a web page to the user as hidden fields in a form. When the user makes a request again, the data in the hidden fields is passed back to the servlet along with any other data that was received in the form.
This technique relies on servlets dynamically creating web pages with hidden forms in them. It does not work with static documents and browser shutdowns.
We will create a very simple OnlineStore cart that allows you to add goods to a OnlineStore basket and review what goods are in there. There are two servlets that are used for this functionality:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class AddToOnlineStoreCart extends HttpServlet {
public void doRetrieve (HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintShopper aPS = response.getWriter();
aPS.println (“<HTML><HEAD><TITLE>OnlineStore Basket"+
" using Hidden Forms"+ "</TITLE></HEAD><BODY>");
aPS.println( "<FORM ACTION='ReviewOnlineStoreCart'"+
" METHOD=GET>" );
aPS.println( "Add to Basket:<BR><BR>" );
aPS.println( "<INPUT TYPE='checkbox' NAME='goods'"+
" VALUE='Pencils $2.0'>Pencils $2<BR>" );
aPS.println( "<INPUT TYPE='checkbox' NAME='goods'"+
" VALUE='Rubbers $30.0'>Rubbers $30<BR>" );
String goods[] = request.getParameterValues( "goods" );
if ( goods != null ) {
for ( int j=0; j < goods.length; j++ ) {
aPS.println( "<INPUT TYPE=hidden NAME=goods"+" VALUE='" + goods[j] + "'>" );
}
}
aPS.println( "<BR><INPUT TYPE=submit"+
" VALUE='View Basket'>" );
}
}
This servlet reads in all the values for the parameter “goods” passed to it via the GET request. It reads the values in using: String goods[] = request.getParameterValues( "goods" );
It creates a web page with this information hidden in hidden fields of a form. The web page also includes check boxes that allow users to select the goods they wish to buy. This page is sent back to the client browser as the response ( See the response argument of doRetrieve method above ).
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class ReviewOnlineStoreCart extends HttpServlet {
public void doRetrieve (HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintShopper aPS = response.getWriter();
aPS.println( "<HTML><HEAD><TITLE>OnlineStore"+
" Basket using Hidden Forms" +"</TITLE></HEAD><BODY>" );
String goods[] = request.getParameterValues( "goods" );
aPS.println( "Basket's contents:<BR><BR>" );
if ( goods == null ) {
aPS.println( "No goods in basket yet" );
}else {
float count = 0;
aPS.println( "<UL>" );
for ( int j=0; j < goods.length; j++ ) {
int positionOfPound = goods[j].indexOf( "$" ) + 1;
String numberStr = goods[j].substring
( positionOfPound );
System.out.println( "positionOfPound = "
+ positionOfPound );
System.out.println( "numberStr = " + numberStr );
float price = Float.parseFloat( numberStr );
count = count + price;
aPS.println( "<LI>" + goods[j] );
}
aPS.println( "<BR><BR>Total: $" + count );
aPS.println( "</UL>" );
}
aPS.println("<FORM ACTION='AddToOnlineStoreCart' METHOD=GET>");
if ( goods != null ) {
for ( int j=0; j < goods.length; j++ ) {
aPS.println("<INPUT TYPE=hidden NAME=goods VALUE='"+
goods[j] + "'>" );
}
}
aPS.println( "<BR><INPUT TYPE=submit VALUE='Add more goods'>" );
aPS.println( "</FORM></BODY></HTML>" );
}
}
This servlet reads the values of the parameter “goods” using: String goods[] = request.getParameterValues( "goods" );
You can retrieve the information using one of the following methods:
* From an xml file
* From a text file/properties file
* From a database
Username & Password
Most HTTP servers have a capability that is inbuilt and restricts access to pages to a set of registered users. We will consider restricting users using Tomcat.
To create a log-in dialog you will need to configure your web server. In the case of Tomcat you will need to edit:
* web.xml
* server.xml
* tomcat-users.xml
When a user is accesing a page that is restricted, HTTP server sends a response asking for a user authentication. A pop up window is the send by the browser for the use to provide a username and a password.
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>Pritt</servlet-name>
<servlet-class>Pritt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Pritt</servlet-name>
<url-pattern>/Pritt</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/Pritt</url-pattern>
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>tomcat</role-name>
<role-name>role1</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Example Basic Authentication Area</realm-name>
</login-config>
</web-app>
Look at the code between the web-resource-collection tags and the code between
login-config.
A URL which has “Pritt” in it ( see ) will require user authentication. The tags show what kinds of request require authentication. The tag define the roles the user authentication requires. More about this in a second.
The file looks like:
<tomcat-users>
<user name="tomcat" password="tomcat" roles="tomcat" />
<user name="role1" password="tomcat" roles="role1" />
<user name="both" password="tomcat" roles="tomcat,role1" />
</tomcat-users>
Note that the users have been given roles. The users must have been assigned the right roles to pass the authentication check. In web.xml shown above in its entirety you will see the following role constraints:
<auth-constraint>
<role-name>tomcat</role-name>
<role-name>role1</role-name>
</auth-constraint>
```
You can add new users. If you assign them either the "tomcat" or "role1" role. You can alternatively create a new role in web.xml.
```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Pritt extends HttpServlet {
static Hashtable users = new Hashtable();
public void doRetrieve (HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintShopper aPS = response.getWriter();
aPS.println( "<HTML><BODY>" );
String remoteUser = request.getRemoteUser();
if ( remoteUser == null ) {
aPS.println("Welcome Anonymous");
}else {
aPS.println( "Welcome " + remoteUser );
Date aDateAccessed = ( Date )users.get( remoteUser );
if ( aDateAccessed == null ) {
aPS.println( "<BR>This is the first time you"+
" have accessed this page" +
" since the Servlet has been running" );
}else {
aPS.println("<BR>You Last accessed this page on " +
aDateAccessed.toString());
}
users.put( remoteUser, new Date() );
}
aPS.println( "</BODY></HTML>" );
}
}
The first time you access the page the output will be:
Welcome role1
This is the first time you have accessed this page since the Servlet has been running. The second time you access the page the output will be something like:
Welcome role1
You Last accessed this page on Wed Apr 26 12:12:30 GMT+02:00 2017
The code that got the username is: String remoteUser = request.getRemoteUser();
Try creating new users and creating log-ins for other servlets if you have time. The hashtable is static for the Servlet Engine may start a new thread running Pritt servlet at any time. As the hashtable is static all threads running the Pritts Servlet will have access to the same hashtable. Instead of using a hashtable to store information it could be more advantageous storing the information in a database. The hashtable lives only as long as the servlet is running. Stopping tomcat will lose data which was in the hashtable. The disadvantage of using user authentication for session tracking is that users have to register.
Conclusion
This guide will make a developer very competent when it comes to creating sessions. It has covered everything, with examples, that is needed for one to create sessions.