Java Tutorial/Servlet/Cookie

Материал из Java эксперт
Перейти к: навигация, поиск

Add Cookie Servlet

   <source lang="java">

import java.io.IOException; import java.io.PrintWriter; 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 AddCookieServlet extends HttpServlet {

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String data = request.getParameter("data");
   Cookie cookie = new Cookie("MyCookie", data);
   response.addCookie(cookie);
   response.setContentType("text/html");
   PrintWriter pw = response.getWriter();
   pw.println("MyCookie has been set to");
   pw.println(data);
   pw.close();
 }

}</source>





Get Cookies Servlet

   <source lang="java">

import java.io.IOException; import java.io.PrintWriter; 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 GetCookiesServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   Cookie[] cookies = request.getCookies();
   response.setContentType("text/html");
   PrintWriter pw = response.getWriter();
   pw.println("<B>");
   for (int i = 0; i < cookies.length; i++) {
     String name = cookies[i].getName();
     String value = cookies[i].getValue();
     pw.println("name = " + name + "; value = " + value);
   }
   pw.close();
 }

}</source>





Get/Set Cookie

   <source lang="java">

import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException
   {
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       
       out.println("<HTML>");
       out.println("<HEAD>");
       out.println("<TITLE>");
       out.println("A Web Page");
       out.println("</TITLE>");
       out.println("</HEAD>");
       out.println("<BODY");
       Cookie[] cookies = request.getCookies();
       boolean foundCookie = false;
       for(int i = 0; i < cookies.length; i++) { 
           Cookie cookie1 = cookies[i];
           if (cookie1.getName().equals("color")) {
               out.println("bgcolor = " + cookie1.getValue());
               foundCookie = true;
           }
       }  
       if (!foundCookie) {
           Cookie cookie1 = new Cookie("color", "cyan");
           cookie1.setMaxAge(24*60*60);
           response.addCookie(cookie1); 
       }
       out.println(">");
out.println("

Setting and Reading Cookies

");
       out.println("This page will set its background color using a cookie when reloaded.");
       out.println("</BODY>");
       out.println("</HTML>");
  }

}</source>





List Servlet Cookie Information

   <source lang="java">

import java.io.IOException; import java.io.PrintWriter; 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 Cookies extends HttpServlet {

 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
     IOException {
   resp.setContentType("text/html");
   req.getSession();
   PrintWriter out = resp.getWriter();
   Cookie cookies[] = req.getCookies();
   out.println("<html>");
   out.println("<head>");
   out.println("<title>Servlet Cookie Information</title>");
   out.println("</head>");
   out.println("<body>");
   if ((cookies == null) || (cookies.length == 0)) {
out.println("

No Cookies found

");
   } else {
out.println("<center>

Cookies found

");
     for (int i = 0; i < cookies.length; i++) {
       Cookie c = cookies[i];
       out.println(c.getName() + "::" + c.getValue() + "::"
           + c.getComment() + "::" + c.getMaxAge() + "
"); }
out.println("</table>
");
   }
   out.println("</body>");
   out.println("</html>");
   out.flush();
 }

}</source>





Parse a Cookie: header into individual tokens according to RFC 2109.

   <source lang="java">

/*

* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* 
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
* 
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
* 
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
* 
* Contributor(s):
* 
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don"t indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/

/*

* Copyright 2004-2005 Sun Microsystems, Inc.  All rights reserved.
* Use is subject to license terms.
*/

import java.lang.System; import java.lang.String; import java.lang.IndexOutOfBoundsException; import java.lang.ArrayIndexOutOfBoundsException; /**

* Parse a Cookie: header into individual tokens according to RFC 2109.
*/

public class CookieTokenizer {

   /**
    * Upper bound on the number of cookie tokens to accept.  The limit is
    * based on the 4 different attributes (4.3.4) and the 20 cookie minimum
    * (6.3) given in RFC 2109 multiplied by 2 to accomodate the 2 tokens in
    * each name=value pair ("JSESSIONID=1234" is 2 tokens).
    */
   private static final int MAX_COOKIE_TOKENS = 4 * 20 * 2;
   /**
    * Array of cookie tokens.  Even indices contain name tokens while odd
    * indices contain value tokens (or null).
    */
   private String tokens[] = new String[MAX_COOKIE_TOKENS];
   /**
    * Number of cookie tokens currently in the tokens[] array.
    */
   private int numTokens = 0;
   /**
    * Parse a name=value pair from the Cookie: header.
    *
    * @param cookies The Cookie: header to parse
    * @param beginIndex The index in cookies to begin parsing from, inclusive
    */
   private int parseNameValue(String cookies, int beginIndex) {
       int length = cookies.length();
       int index = beginIndex;
       while (index < length) {
           switch (cookies.charAt(index)) {
           case ";":
           case ",":
               // Found end of name token without value
               tokens[numTokens] = cookies.substring(beginIndex, index).trim();
               if (tokens[numTokens].length() > 0) {
                   numTokens++;
                   tokens[numTokens] = null;
                   numTokens++;
               }
               return index + 1;
           case "=":
               // Found end of name token with value
               tokens[numTokens] = cookies.substring(beginIndex, index).trim();
               numTokens++;
               return parseValue(cookies, index + 1);
           case """:
               // Skip past quoted span
               do index++; while (cookies.charAt(index) != """);
               break;
           }
           index++;
       }
       if (index > beginIndex) {
           // Found end of name token without value
           tokens[numTokens] = cookies.substring(beginIndex, index).trim();
           if (tokens[numTokens].length() > 0) {
               numTokens++;
               tokens[numTokens] = null;
               numTokens++;
           }
       }
       return index;
   }
   /**
    * Parse the name=value tokens from a Cookie: header.
    *
    * @param cookies The Cookie: header to parse
    */
   public int tokenize(String cookies) {
       numTokens = 0;
       if (cookies != null) {
           try {
               // Advance through cookies, parsing name=value pairs
               int length = cookies.length();
               int index = 0;
               while (index < length)
                   index = parseNameValue(cookies, index);
           }
           catch (ArrayIndexOutOfBoundsException e) {
               // Filled up the tokens[] array
           }
           catch (IndexOutOfBoundsException e) {
               // Walked off the end of the cookies header
           }
       }
       return numTokens;
   }
   /**
    * Return the number of cookie tokens parsed from the Cookie: header.
    */
   public int getNumTokens() {
       return numTokens;
   }
   /**
    * Returns a given cookie token from the Cookie: header.
    *
    * @param index The index of the cookie token to return
    */
   public String tokenAt(int index) {
       return tokens[index];
   }
   /**
    * Parse the value token from a name=value pair.
    *
    * @param cookies The Cookie: header to parse
    * @param beginIndex The index in cookies to begin parsing from, inclusive
    */
   private int parseValue(String cookies, int beginIndex) {
       int length = cookies.length();
       int index = beginIndex;
       while (index < length) {
           switch (cookies.charAt(index)) {
           case ";":
           case ",":
               // Found end of value token
               tokens[numTokens] = cookies.substring(beginIndex, index).trim();
               numTokens++;
               return index + 1;
           case """:
               // Skip past quoted span
               do index++; while (cookies.charAt(index) != """);
               break;
           }
           index++;
       }
       // Found end of value token
       tokens[numTokens] = cookies.substring(beginIndex, index).trim();
       numTokens++;
       return index;
   }

}</source>





Servlet Cookie Reader

   <source lang="java">

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("

The name and value of each found cookie

");
        for (int i = 0; i < cookies.length; i++){
           cookie = cookies[i];
           out.println("Name of cookie #"+(i + 1)+": "+cookie.getName()+"
"); out.println("Value of cookie #"+(i + 1)+": "+cookie.getValue()+"

"); } } else {
out.println("

This request did not include any cookies

");
       }
     
       out.println("</body>");
       out.println("</html>");
   
       out.close();
   } 
   
   public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, java.io.IOException {
       
       doGet(request,response);
   } 

}</source>





Servlet Cookie Setter

   <source lang="java">

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 newCookie = false;
   
   //Get the "mycookie" Cookie if it exists
   if (cookies != null){
       for (int i = 0; i < cookies.length; i++){
           if (cookies[i].getName().equals("mycookie")){
             cookie = cookies[i];
            } 
       }//end for
   }//end if
      
   if (cookie == null){
      newCookie=true;
     //Get the cookie"s Max-Age from a context-param element
     //If the "cookie-age" param is not set properly
     //then set the cookie to a default of -1, "never expires"
     int maxAge;
     try{
          maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
          } catch (Exception e) {
           maxAge = -1;
          }
     
      //Create the Cookie object
    
       cookie = new Cookie("mycookie",""+getNextCookieValue());
       cookie.setPath(request.getContextPath());
       cookie.setMaxAge(maxAge);
       response.addCookie(cookie);
       
       }//end if
       // get some info about the cookie
       response.setContentType("text/html");
       java.io.PrintWriter out = response.getWriter();
   
       out.println("<html>");
       out.println("<head>");
       out.println("<title>Cookie info</title>");  
       out.println("</head>");
       out.println("<body>");
       
out.println("

Information about the cookie named \"mycookie\"

");
       out.println("Cookie value: "+cookie.getValue()+"
"); if (newCookie){ out.println("Cookie Max-Age: "+cookie.getMaxAge()+"
"); out.println("Cookie Path: "+cookie.getPath()+"
"); } out.println("</body>"); out.println("</html>"); out.close(); } private long getNextCookieValue(){ /*This produces a cookie value to show how to create Cookie objects. If this method was heavily used in a production environment it may produce too many objects; synchronization of a single Date object might be better, based on performance testing. At any rate a production environment would produce a unique cookie value in a different manner such as from a unique database ID. */ //returns the number of milleseconds since Jan 1, 1970 return new java.util.Date().getTime(); }
   public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, java.io.IOException {
       
       doGet(request,response);
   } 

}</source>