Servlet Cookie Reader : Cookie « Servlet « Java Tutorial






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class MyServlet extends HttpServlet {
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    
    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean hasCookies = false;
    
  if (cookies != null)
        hasCookies = true;
   
        // display the name/value of each cookie
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
    
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Cookie information</title>");  
        out.println("</head>");
        out.println("<body>");
        if (hasCookies){
        out.println("<h2> The name and value of each found cookie</h2>");
        
         for (int i = 0; i < cookies.length; i++){
            cookie = cookies[i];
            out.println("Name of cookie #"+(i + 1)+": "+cookie.getName()+"<br>");
            out.println("Value of cookie #"+(i + 1)+": "+cookie.getValue()+"<br><br>");
      
       }
        
        } else {
            out.println("<h2> This request did not include any cookies</h2>");
        }
      
        out.println("</body>");
        out.println("</html>");
    
        out.close();
    } 
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        
        doGet(request,response);
    } 
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>
        <init-param>
            <param-name>
                go
            </param-name>
            <param-value>
                weather
            </param-value>
        </init-param>
             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletCookieReader.zip( 89 k)








25.4.Cookie
25.4.1.Add Cookie Servlet
25.4.2.Get Cookies Servlet
25.4.3.Servlet Cookie Setter
25.4.4.Servlet Cookie Reader
25.4.5.Get/Set Cookie
25.4.6.List Servlet Cookie Information
25.4.7.Parse a Cookie: header into individual tokens according to RFC 2109.