Use cookie to save session data : Session « Servlets « Java

Use cookie to save session data


import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerCookie extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    PrintWriter out = res.getWriter();

    String sessionid = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("sessionid")) {
          sessionid = cookies[i].getValue();

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
      sessionid = generateSessionId();
      Cookie c = new Cookie("sessionid", sessionid);

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
    } else {
      for (int i = 0; i < items.length; i++) {
        out.println("<LI>" + items[i]);

    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");

    // Offer a help page.
    out.println("For help, click <A HREF=\"/servlet/Help"
        + "?topic=ShoppingCartViewerCookie\">here</A>");


  private static String generateSessionId() throws UnsupportedEncodingException {
    String uid = new java.rmi.server.UID().toString(); // guaranteed unique
    return URLEncoder.encode(uid,"UTF-8"); // encode any special chars

  private static String[] getItemsFromCart(String sessionid) {
    return new String[]{"a","b"};  


Related examples in the same category

1.Using Sessions in Servlet
2.Session Tracker
3.Servlet: simple session
4.Session logger
5.Servlet: Session display
6.Servlet: session listener
7.Servlet : session filter
8.Servlet: session attribute listener
9.Servlet: Session bind listener
10.Servlet Session Example
11.Use hidden fields to save session data
12.Use URL rewrite to save session data
13.Session Events: implements HttpSessionBindingListener
14.Session Expiration Filter
15.Map adaptor for HttpSession objects
16.Fake session