JSP Hosting
 

HostingServicesSupportOrderAbout UsSoftwareHome


Even experts read the manuals. Our tech support staff has most of the books that are out on a wide variety of web topics. Here are some of their top picks. We think you'll find them useful and informative as well.



Storing session data

One of the most common things servlets are required to do is to store data throughout a user's session. Servlets take the drudgery out of tracking user sessions by offering an HttpSession object which you can use to conveniently store data. Programmers accustomed to storing data in CGI URLs will be overjoyed to know how easily they can store and access session data.

The following example initializes a session when the user POSTs from the form in our previous example. When the user loads the page via a GET request, the servlet shows the session data previously provided.

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


// MyServlet.java



public class MyServlet extends HttpServlet
{ 
 public void doGet ( HttpServletRequest req, HttpServletResponse res ) 
 throws ServletException, IOException { 
  HttpSession session = req.getSession(true);
  res.setContentType( "text/html"); 
  PrintWriter out = res.getWriter(); 
  out.println( "<html><body>" );          
  out.println( "Hello there, " + session.getValue("name")); 
  out.println( "Address: " + session.getValue("address")); 
  out.println( "City: " + session.getValue("city")); 
  out.println( "Phone: " + session.getValue("phone")); 
  out.close(); 
 } 

 public void doPost ( HttpServletRequest req, HttpServletResponse res ) 
 throws ServletException, IOException { 
  HttpSession session = req.getSession(true);
  session.putValue("name",req.getParameter("name")); 
  session.putValue("address",req.getParameter("address")); 
  session.putValue("city",req.getParameter("city")); 
  session.putValue("phone",req.getParameter("phone")); 
  res.setContentType( "text/html"); 
  PrintWriter out = res.getWriter(); 
  out.println( "<html><body>" );          
  out.println( "Your post has been received.");
  out.close(); 
 } 

}

Use the following HTML form to post data to this servlet and load it using the standard URL to view the session contents.

<FORM METHOD=POST ACTION=http://www.yourdomain.com/servlet/MyServlet">
<INPUT TYPE=text NAME=name> Name<BR>
<INPUT TYPE=text NAME=address> Address<BR>
<INPUT TYPE=text NAME=city> City<BR>
<INPUT TYPE=text NAME=phone> Phone<BR>
<INPUT TYPE=submit>
          

 

<- Previous | Next ->

Note: MMA technical support staff cannot provide troubleshooting of problems with third-party CGI scripts including but not limited to: Perl scripts, C/C++ binaries, PHP or web/database integration unless these services are specifically contracted. For these services, please see our Quote Request Form.


Copyright © 1995-2012
Motivational Marketing Associates, LLC
All Rights Reserved.