Re: pls help w/cookies.......

From: Juha Laiho (Juha.Laiho_at_iki.fi)
Date: 01/27/05


Date: Thu, 27 Jan 2005 21:17:01 +0000 (UTC)

Frances Del Rio <fdr58@yahoo.com> said:
>this is all just a learning exericse, to keep it simle at first I want
>to do form where user types in name then when they visit pg next time
>their name shows up on page..

I built a hopefully minimalistic enough demo on how to handle data
within a session.

First, there's a plain HTML page, a form that the user fills in.

The form is posted to a handler servlet (just something I made up),
which will read and store the form values (the values will be stored
into a session object in the server side).

Third, the output of the handler servlet contains a link to a viewer
servlet, which will display the value as retrieved from the session
object, and invalidate the session (so, if you reload the viewer page,
it'll show the value as null).

Place the files in a hierarchy as follows:
sessiondemo/index.html
sessiondemo/WEB-INF/classes (empty directory)
sessiondemo/WEB-INF/web.xml
sessiondemo/src/sd/Handler.java
sessiondemo/src/sd/Viewer.java

Compile sd.Handler and sd.Viewer so that the .class files end up in
directory sessiondemo/WEB-INF/classes/sd ; at this point you should
have a working web application set-up.

(more text after the sources)

index.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <title>SessionDemo Form</title>
  </head>
  <body>
  <form method="POST" action="handler">
  Data: <input type="TEXT" name="data_field"><br>
  <input type="SUBMIT">
  </form>
  </body>
</html>

src/sd/Handler.java:
package sd;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class Handler extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String data = request.getParameter("data_field");

        request.getSession().setAttribute("data_attr",data);
        
        out.println("<html><head><title>Handler</title></head><body>");
        out.println("Data received: \"" + data + "\"<br>");
        out.println("Now, look at it vith the <a href=\"viewer\">viewer</a>");
         
        out.println("</body></html>");

        out.close();
    }
    
}

src/sd/Viewer.java:
package sd;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class Viewer extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        String data = (String) request.getSession().getAttribute("data_attr");

        out.println("<html><head><title>Viewer</title></head><body>");
        out.println("Data retrieved: \"" + data + "\"");
         
        out.println("</body></html>");

        out.close();
        
        request.getSession().invalidate();
    }
}

WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!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>Handler</servlet-name>
    <servlet-class>sd.Handler</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>Viewer</servlet-name>
    <servlet-class>sd.Viewer</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Handler</servlet-name>
    <url-pattern>/handler</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Viewer</servlet-name>
    <url-pattern>/viewer</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>
            30
        </session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>
            index.html
        </welcome-file>
  </welcome-file-list>
</web-app>

... ok, then. Shouldn't be too much code, at least. How does this work?

Showing the posted data from the servlet should be evident. Now, the
handler servlet also set up a session on the server side, and stored
the data value into the session object (with name data_attr; the name
could've been anything). The HTTP response from the POST request will
also set a cookie (with name JSESSIONID) to the browser. The value of
this cookie is the session identifier generated by the servlet engine.

Then, when you go to the viewer page, your browser will still remember
the JSESSIONID cookie, and will send it to the server -- and by that
session id the viewer servlet can find the data from the session object
(so, the same data that was stored in the handler servlet).

This is what I meant by letting the servlet engine handle the data
for you. The only information that is continually transmitted between
the browser and the server is the session id; everything else is stored
on the server on behalf of the client, and accessible only for clients
presenting the correct JSESSIONID cookie.

As you can see from the above, you can have an "indefinite" amount of
data stored in the session object; just keep good count on which names
you're using -- and clean up the values you don't need any more with the
removeAttribute() method. The invalidate() method makes for a good way
to implement the session logout feature.

Also, there's no requirement for the data to be stored as String objects;
if you have numeric data, you can store it as Integer objects. So,
parse from the text form when the data is initially received, and store
in whatever format makes most sense for future processing.

-- 
Wolf  a.k.a.  Juha Laiho     Espoo, Finland
(GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V
         PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++
"...cancel my subscription to the resurrection!" (Jim Morrison)


Relevant Pages

  • Re: How to re-use existing classes in JSP/JavaBeans/Servlets
    ... I want to instantiate them and have the instance ... so the lifecycle is that of the client session. ... Process all data that comes in a HTTP request within a servlet -- they're ... are a good match with JSPs, and JSPs are good for creating HTML views. ...
    (comp.lang.java.programmer)
  • Re: Servlet design question
    ... don't put huge objects in the session, ... Concerning fields in the servlet class itself, no, you shouldn't do it, ... > for that request only (e.g. request-related stuff scooped out of ... > wrapper also contains a reference to my SessionState object, ...
    (comp.lang.java.programmer)
  • Re: TOMCAT PROBLEM: Establishing a session
    ... > I have a java applet running inside the html produced by the java ... > servlet, we have written a second servlet which implements a HashTable ... Do note that where sessions are maintained via a session cookie, ... You must also take care when trying to pass request parameters ...
    (comp.lang.java.programmer)
  • Re: Share a Session
    ... >> You could write the sessionID into the applet tag as a parameter. ... > How exactly do I use the session id from the applet? ... same name that the servlet normally uses which is "JSESSIONID" ... will let you set a cookie header - I don't remember the exact ...
    (comp.lang.java.help)
  • Re: Using getOutputStream with a servlet redirect?
    ... > I want to pass information from my servlet into one of my JSP ... > pages but the Session object doesen't seem to be working for my ... You are getting a new session for each request because the requests do ...
    (comp.lang.java.programmer)