现在的位置: 首页 > 综合 > 正文

JSP中Cookie的用法

2013年11月05日 ⁄ 综合 ⁄ 共 668字 ⁄ 字号 评论关闭

 

<%@page contentType="text/html;charset=GB2312"%>
<%
  int counter = 0;
  //得到所有的Cookie
  //与其它内置对象不同,Cookie首字母大写
  Cookie cookies[] = request.getCookies();
  //request对象获取Cookie
  if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
      if (cookies[i].getName().equals("counter"))
        counter = Integer.parseInt(cookies[i].getValue()) + 1;
    }
  }
  // 首次登陆,需要创建Cookie ; 以后登陆,需更新Cookie
  Cookie c = new Cookie("counter", "" + counter);
  c.setMaxAge(60 * 60 * 24 * 365); //设置Cookie有效期
  response.addCookie(c);
  //response对象添加Cookie
%>
<html>
  <head>
    <title>    </title>
  </head>
  <body bgcolor="#FFFFFF">
  <%
    if (counter == 0)
      out.println("First!Welcome!");
    else
      out.println(counter + " times!");
  %>
  </body>
</html>  

抱歉!评论已关闭.