You will learn how to use information stored in the session build when a user activates a servlet. You will also learn how to create and access cookies. Both of these techniques allow your servlet to retain information either for the duration of a single session or for the length of time a cookie resides on the users computer.
Cookies are small files that servlets create on the client's computer. These files contain information that may be accessed during the current browsing session or future browsing sessions. This information is typically used to trace the clients past sessions to direct the client to familar areas. It can also be used to fill in information in a form to save the user time.
In our problem, you will create a servlet that has both doPost and doGet methods. It will register a user and send a cookie back to the user with the users password. This password will be stored using the users name as the cookie name. When the user tries to logon, the cookies are retrieved and the
| 1. Register |
|
| 2. If the user accepts cookies-welcome the user | |
| 3. If the user does not accept cookies-indicate this | |
| 4. Login- after registration allow login | |
| 5. If successful - welcome | |
| 6. Otherwise indicate failure | |
One obvious reason for not using this technique for storing passwords is the page returned by a successful login. The address includes the password in plain text. If logins are in a public area this would not preserve the privacy of the user. The solution to this is of course to use Post for any servlets that handle sensitive information.
On the other hand, this is a good illustration of how cookies work, since it is very simple.
Create a servlet with both the doPost and doGet methods. Add parameters userName and passWord to the doPost method using the servlet Wizzard. This servlet will create two cookies. The first holds the name of the user and the second holds the password.
The constructor for a Cookie takes two strings as parameters. The first is the name of the Cookie (used to locate the cookie) and the second is the value stored in the Cookie. In the code below you see the first cookie has name, "Name" and stores the users name. In additon, the maximum age (expiration date) is set to 360 (360 seconds). Finally the cookie is sent by calling the addCookie function. The three lines that create and send the cookie are:
Cookie c = new Cookie("Name" ,userName);
c.setMaxAge(360);
response.addCookie(c);
The cookie containing the password is created in much the same way except that it uses the variable userName as the name of the cookie. Once the cookies have been sent, you will want to know if the user's browser can receive cookies. To do this create an array of cookies and use request to retrieve the cookies at the site.
Cookie testCookie[]=request.getCookies();
If the array is null, inform the user that they cannot register unless they have cookies enabled. The html code you must add to the page generated by the wizzard is the following:
if (testCookie!=null )
out.println("Thanks for registering " +userName);
else
out.println("< H3>Sorry you must allow cookies to register< /H3>" );
If the user's browser accepts cookies, send a thank you and if not send regrets.
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Name passed around
String userName = "" ;
try { userName = request.getParameter("userName" ); } catch (Exception e) { e.printStackTrace(); }
//user Password
String passWord = "" ;
try { passWord = request.getParameter("passWord" ); } catch (Exception e) { e.printStackTrace(); }
Cookie c = new Cookie("Name" ,userName);
c.setMaxAge(360);
response.addCookie(c);
c = new Cookie(userName,passWord);
c.setMaxAge(360);
response.addCookie(c);
Cookie testCookie[]=request.getCookies();
response.setContentType("text/html" );
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("< html>" );
out.println("< head>< title>CookieServlet< /title>< /head>" );
out.println("< body>" );
if (testCookie!=null )
out.println("Thanks for registering " +userName);
else
out.println("< H3>Sorry you must allow cookies to register< /H3>" );
out.println("< /body>< /html>" );
out.close();
}
This doGet method is similar to a doPost in that it retrieves the user name and password as well as the cookies the doPost routine sent. The interesting part of this problem is the search for the password in the array of cookies. Recall that the name of the cookie is the user name (which you just retrieved from the login page. Set the password to the empty string and if there is no password in the cookies (this cookie expired), the value of passWord will be the empty string and an appropriate web page will be made. Notice to test equality you have to use the equals function. This is necessary, since == only tests if the objects are identical (have the same address). If you find the cookie with userName as its name, the passWord is retrieved using the getValue function. Finally, when you generate the web page response, the login is successful only if passWord.equals(enteredPassWord). If not the login fails and the user is informed that the password is incorrect or has expired.
String passWord = "" ;
int i=0;
if (cookies !=null)
for (;i< cookies.length; i++) {
if (userName.equals(cookies[i].getName()))
passWord = cookies[i].getValue();
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html" );
Cookie cookies[];
cookies = request.getCookies();
String userName = request.getParameter("userName" );
String enteredPassWord = request.getParameter("passWord" );
String passWord = "" ;
int i=0;
if (cookies !=null)
for (;i< cookies.length; i++) {
if (userName.equals(cookies[i].getName()))
passWord = cookies[i].getValue();
}
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("< html>" );
out.println("< head>< title>CookieServlet< /title>< /head>" );
out.println("< body>" );
if (passWord.equals(enteredPassWord))
out.println("You are now logged on "+userName );
else
out.println("Sorry " +userName +" your password is incorrect or expired" );
out.println("< /body>< /html>" );
out.close();
}
Cookies are frequently used to store the user name and password for web sites. As you have seen above misuse of this information by the programmer can lead to the password being printed in the address field of the browser. The advantage of using cookies for passwords is that the user can log on without having to reenter their password. This cuts down on the possiblity that a request for passwords will take place on an unencripted transmission.
Cookies can only be accessed from the outside by the site that created them, but anyone with access to the user's machine has access to the cookies and might learn sensitive information from these cookies. In addition many users do not accept cookies as a matter of privacy, since cookies are used to gather information about the user's viewing habits.If a user is not accepting cookies, they cannot get a password with this system. One other reason for storing passwords in cookies is that as the user moves from page to page in a large site, they change servlets. Each servlet can check the password without requiring that it be reentered. The next section has a simpler solution to this problem.
To get the complete code for this project including all web pages click here .
When you connect to a web site, you start a session. Sessions contain the information needed to maintain the connection between your computer and the web site. They also provide a place for servlets to store information. This information is available as long as you maintain a session with a page (or servlet) at the site. When you move on the session is terminated. Java allows you to store data in the session. An example is the shopping cart. When you are at your favorite e-commerce site, you may start by shopping for books and place a few in you shopping cart. Then you move on to CDs and place a few in your shopping cart. This shopping cart is passed from servlet to servlet in the session.
Java sessions are created and accessed by the getSession methods of the HTTPServletResponse and HTTPServletRequest classes. This method takes a boolean parameter. If the parameter is true, and a session was created by a previous request that session is retrieved otherwise a new session is created. If the parameter is false, previously created sessions are retrieved, but no new ones are created.
Once a session has been created, data of various types can be stored in the session by the putValue session method and retrieved using the getValue method. The getValue method relies on a value name to retrieve the data. Creating unique value names is difficult. In the example given here, the session Id was retrieved and used as a name. You could also take the session number and concatenate it with the name of the data item you are saving, if you are saving more than one piece of data. You can retrieve the session value names using the method getValueNames. This function returns an array of strings. You can either get the names of the items stored in the session, or simply use the length property of the array to find out how many names there are.
This is a very simple program that allows a user to move from web page to web page an be addressed by name in these pages. You may try running the second page that is in the zip file without running the first, to see that the data is only present during a run initiated through the first page.
The doPost method collects the users name and stores it in the current session. Notice that this method creates a session if one does not exist and stores the users name with the session id as valueName. To get the session id, use the getId of Session.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true );
//name of the user passed between HTML pages
String userName = "" ;
try { userName = request.getParameter("userName" ); } catch (Exception e) { e.printStackTrace(); }
session.putValue(session.getId(),userName);
response.setContentType("text/html" );
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("< html>" );
out.println("< head>< title>Servlet1< /title>< /head>" );
out.println("< body>" );
out.println("Ok " + userName + " open the page < A HREF = file://D:/cs331/Projects/SimpSess/SeeName.htm>SeeName.htm< /A> to see the results" );
out.println("< /body>< /html>" );
out.close();
}
The SeeName page calls on the doGet method of this servlet
The doGet method gets a session if one exists (the parameter of getSession is false). If the session exists, it uses the session id to retrieve the users name and uses it to greet the user.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false );//don't create if doesn't exits
String name;
if (session != null )
name= (String)session.getValue(session.getId());
else
name = null ;
response.setContentType("text/html" );
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("< html>" );
out.println("< head>< title>Servlet1< /title>< /head>" );
out.println("< body>" );
if (name != null )
out.println("< H1>Hi " +name+" how are you< /H1>" );
else
out.println("< H1>Can't tell who you are. Your session must have expired< /H1>" );
out.println("< /body>< /html>" );
out.close();
}