Servlet - Использование Cookie для запоминания состояния

В примере с cookies использовались сервлеты SetCookies, устанавливающий Cookie, и GetCookies, читающий Cookie. Действия, выполняемые сервлетом SetCookies: Сервлет GetCookies читает значение параметра (data1) и, в зависимости от его значения, выполняет следующие действия:


Листинг сервлета SetCookies.java
 
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
 
public class SetCookies extends HttpServlet implements Serializable
{
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
  {
   String[][] cookies ={{"c1", "My first cookie" }, {"color1", "aabbcc"}, {"color2", "ffaa77"}};
 
   for (int i = 0; i < cookies.length; i++)
   {
    Cookie ck = new Cookie (cookies[i][0], cookies[i][1]);
    ck.setMaxAge (60);
    resp.addCookie (ck);
   }
 
   resp.setContentType("text/html;charset=windows-1251");
 
   PrintWriter out = resp.getWriter();
 
   out.println( "<html>" +
     "<head>" +
      "<title>Cookies List</title>" +
     "</head>" +
     "<body bgcolor=#fff1df>" +
      "<form name=Form1 method=GET " +
      "action=http://localhost:8082/servlets-labir/Recall>"
   );
   out.println("<h3>" + cookies.length + " Cookies found</h3>");
   out.println ("<table cellspacing = 5>" +
     "<tr align = left>" +
      "<th>Наименование</th>" +
      "<th>Значение</th>" +
     "</tr>"
   );
   for (int i = 0; i < cookies.length; i++)
   {
    out.println("<tr><td>" + cookies[i][0] + "</td>" +
      "<td>" + cookies[i][1] + "</td></tr>"
   }
   out.println ("</table>");
   out.println("<p>" + "<h3>Отправьте Web-серверу одну из позиций :</h3><p>" +
     " input type=text name=data1><p>" +
     " input type=submit value=\"Send\">" +
     " /form> /body> /html>" +
   );
   out.close();
  }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Листинг сервлета GetCookies.java
 
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
 
public class GetCookies extends HttpServlet implements Serializable
{
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
  {
   String msg = req.getParameter("data1");
   Cookie[] cookies = req.getCookies();
   if (msg.length() == 0)
    resp.sendRedirect("http://localhost:8082/servlets-labir/hello");
   else if ((cookies == null) || ((!msg.equals("c1" )) && (!msg.equals("color1")) && (!msg.equals("color2"))))
    resp.sendRedirect("http://localhost:8082/servlets-labir/Draw?data1=" + msg);
   else
   {
    String color1 = null;
    String color2 = null;
    for (int i = 0; i < cookies.length; i++)
    {
     if (cookies[i].getName().equals("color1"))
      color1 = cookies[i].getValue();
     else if (cookies[i].getName().equals("color2"))
      color2 = cookies[i].getValue();
    }
    resp.setContentType("text/html;charset=windows-1251");
    PrintWriter out = resp.getWriter();
    out.println ("<html><head>" +
      "<title>Read Cookies List" +
     "</head>" +
    );
    if ((msg.equals("color1")) || (msg.equals("color2")))
    {
     if (msg.equals("color1"))
      out.println("<body bgcolor=#" + color1 + ">");
     else
      out.println("<body bgcolor=#" + color2 + ">");
    }else
     out.println("<body bgcolor=#ff1fdf>");
     if (cookies.length == 0){
      out.println("<h3> No cookies found!</h3>");
     }else{
      out.println("<h3>" + cookies.length + " Cookies found</h3>");
      out.println ("<table cellspacing = 5>" +
       "<tr align = left>" +
       "<th>Наименование /th>" +
       "<th>Значение /th>" +
       "</tr>"
      );
      for (int i = 0; i < cookies.length; i++)
      {
       out.println("<tr><td>" + cookies[i].getName() + "</td>" +
       "<td>" + cookies[i].getValue() + "</td></tr>");
      }
      out.println ("</table>");
     }
     out.println("</body></html>");
     out.close();
    }
   }
  }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Код объявления сервлетов SetCookies и GetCookies в дескрипторе поставки web.xml
 
<servlet>
  <servlet-name>Remember</servlet-name>
  <servlet-class>SetCookies</servlet-class>
</servlet>
<servlet>
  <servlet-name>Recall</servlet-name>
  <servlet-class>GetCookies</servlet-class>
</servlet>
 
<servlet-mapping>
  <servlet-name>Remember</servlet-name>
  <url-pattern>/Remember</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>Recall</servlet-name>
  <url-pattern>/Recall</url-pattern>
</servlet-mapping>


Партнеры:


Rambler's Top100 Рейтинг@Mail.ru