java cookie教程_[Java教程]cookie案例

[Java教程]cookie案例

0 2015-05-19 00:02:05

Summary:

cookie是以字符串的形式保存数据的,把数据保存在客户端.

一个cookie只能标识一种信息,它至少包含有一个标识该信息的名称(name)和设置值(value)

setMaxAge(0)//可以删除cookie,用JavaScript也可以删除

//常用的方法

setMaxAge()//设置最大的有效期

setValue()|getValue()

getName();

setPath()|getPath()

/**

* cookie测试

* @author 邵海雄

* @date   2015-5-18  下午07:12:33

*/

public class CookieServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

out.print("你上次访问的时间是:");

//获取用户时间的cookie

Cookie cookies[] =request.getCookies();

for (int i = 0;cookies!=null&& i < cookies.length; i++) {

if (cookies[i].getName().equals("lastAccessTime")) {

//得到用户上次的访问时间

long cookieValue = Long.parseLong(cookies[i].getValue());

Date date = new Date(cookieValue);

out.print(DateFormat.getDateInstance().format(date));

}

}

//给用户回送最新访问的时间

Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");

//设置有效期

cookie.setMaxAge(1*30*24*3600);//1*30*24*3600   这是一个月的时间

//设置cookie保存的路径

cookie.setPath("/Cookie");

//添加Cookie

response.addCookie(cookie);

}

} 本文网址:http://www.shaoqun.com/a/117182.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

ie

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值