JSP Cookie processing

Cookie is a text file stored on the client machine, they save a lot of track information. In the Servlet technology, based on, JSP apparently able to provide support for the HTTP cookie.

There are generally three steps to identify repeat:

  1. Server script sends a series of cookie to the browser. Such as name, age, ID number, and so on.
  2. Browser stores this information in a local machine, a rainy day.
  3. The next time the browser sends a request to the server any, it will also send the cookie information to the server, and the server uses this information to identify the user or to do some other things.

JSP Cookie process needs to be Chinese encoding and decoding

String   str   =   java.net.URLEncoder.encode("中文", "UTF-8");            //编码
String   str   =   java.net.URLDecoder.decode("编码后的字符串","UTF-8");   // 解码
(1)创建一个 cookie 对象
Cookie cookie = new Cookie("key","value");

(2) 设置有效期:调用 setMaxAge() 函数表明 cookie 在多长时间(以秒为单位)内有效。下面的操作将有效期设为了 24 小时。
cookie.setMaxAge(60*60*24); 

(3) 将 cookie 发送至 HTTP 响应头中:调用 response.addCookie() 函数来向 HTTP 响应头中添加 cookie。
response.addCookie(cookie);

示例
<%
   // 编码,解决中文乱码   
   String str = URLEncoder.encode(request.getParameter("name"),"utf-8");  
   // 设置 name 和 url cookie 
   Cookie name = new Cookie("name",
           str);
   Cookie url = new Cookie("url",
              request.getParameter("url"));

   // 设置cookie过期时间为24小时。
   name.setMaxAge(60*60*24); 
   url.setMaxAge(60*60*24); 

   // 在响应头部添加cookie
   response.addCookie( name );
   response.addCookie( url );
%>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // 获取 cookies 的数据,是一个数组
   cookies = request.getCookies();
   if( cookies != null ){
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         out.print("参数名 : " + cookie.getName());
         out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8"));
      }
  }else{
      out.println("没有发现 Cookie");
  }
%>
删除 cookie 非常简单。如果您想要删除一个 cookie,按照下面给的步骤来做就行了:
    获取一个已经存在的 cookie 然后存储在 Cookie 对象中。
    将 cookie 的有效期设置为 0。
    将这个 cookie 重新添加进响应头中。

<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // 获取当前域名下的cookies,是一个数组
   cookies = request.getCookies();
   if( cookies != null ){
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         if((cookie.getName( )).compareTo("name") == 0 ){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("删除 Cookie: " + 
            cookie.getName( ) + "<br/>");
         }
      }
  }else{
      out.println("没有发现 Cookie");
  }
%>

Guess you like

Origin www.cnblogs.com/loveer/p/11346347.html
jsp