Java Tutorial/Servlet/Cookie

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Add Cookie Servlet

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("<B>MyCookie has been set to");
    pw.println(data);
    pw.close();
  }
}





Get Cookies Servlet

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();
  }
}





Get/Set Cookie

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("<H1>Setting and Reading Cookies</H1>");
        out.println("This page will set its background color using a cookie when reloaded.");
        out.println("</BODY>");
        out.println("</HTML>");
   }
}





List Servlet Cookie Information

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("<center><h1>No Cookies found</h1>");
    } else {
      out.println("<center><h1>Cookies found</h1>");
      for (int i = 0; i < cookies.length; i++) {
        Cookie c = cookies[i];
        out.println(c.getName() + "::" + c.getValue() + "::"
            + c.getComment() + "::" + c.getMaxAge() + "<BR/>");
      }
      out.println("</table></center>");
    }
    out.println("</body>");
    out.println("</html>");
    out.flush();
  }
}





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

/*
 * 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;
    }
}





Servlet Cookie Reader

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);
    } 
}





Servlet Cookie Setter

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("<h2> Information about the cookie named \"mycookie\"</h2>");
        
        out.println("Cookie value: "+cookie.getValue()+"<br>");
        if (newCookie){
        out.println("Cookie Max-Age: "+cookie.getMaxAge()+"<br>");
        out.println("Cookie Path: "+cookie.getPath()+"<br>");
        }
        
        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);
    } 
}