cookieutilities.java

来自「servletjsp一些应用程序」· Java 代码 · 共 57 行

JAVA
57
字号
package coreservlets;import javax.servlet.*;import javax.servlet.http.*;/** Two static methods for use in cookie handling. *  <P> *  Taken from Core Servlets and JavaServer Pages 2nd Edition *  from Prentice Hall and Sun Microsystems Press, *  http://www.coreservlets.com/. *  &copy; 2003 Marty Hall; may be freely used or adapted. */public class CookieUtilities {    /** Given the request object, a name, and a default value,   *  this method tries to find the value of the cookie with   *  the given name. If no cookie matches the name,   *  the default value is returned.   */    public static String getCookieValue                           (HttpServletRequest request,                            String cookieName,                            String defaultValue) {    Cookie[] cookies = request.getCookies();    if (cookies != null) {      for(int i=0; i<cookies.length; i++) {        Cookie cookie = cookies[i];        if (cookieName.equals(cookie.getName())) {          return(cookie.getValue());        }      }    }    return(defaultValue);  }  /** Given the request object and a name, this method tries   *  to find and return the cookie that has the given name.   *  If no cookie matches the name, null is returned.   */    public static Cookie getCookie(HttpServletRequest request,                                 String cookieName) {    Cookie[] cookies = request.getCookies();    if (cookies != null) {      for(int i=0; i<cookies.length; i++) {        Cookie cookie = cookies[i];        if (cookieName.equals(cookie.getName())) {          return(cookie);        }      }    }    return(null);  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?