【Java学习笔记】Cookie Session Application

1.Cookie:

  • Cookie 是保存到客户端的的一个文本文件,与特定的用户相关,以键---值对的形式存放

创建Cookie的方法:Cookie cookie = new Cookie(name ,value);其中name和value 都是String的类型,可以用setXXX getXXX方法设置Cookie的属性和获得属性,然后再利用HttpServletResponse的方法

addCookie(Cookie)将它设置到客户端。

  • 利用HttpServletRequest的getCookies()方法读取客户端的所有Cookie,返回一个Cookie数组

2.Session

  • 存储Session的两种方法:将Session写到浏览器的Cookie中     
                                                  通过URL的重写
  • 建立一个Session的方法,HttpSession mySession = request.getSession(true);
  • Session是写在服务器的文件,mySession 具有相应的方法设置Session的属性(比如存活时间)
  • 通过response.encodeURL() 转码,将URL后面加上SessionId,如果浏览器没有禁用Cookie的话,就将Session写到Cookie中

3.Application

 

  • 用于保存整个WebApplication的生命周期内部都可以访问的数据,即保存在服务器
  • 在API中表现为ServletContext,通过HttpServlet的getServletContext方法可以拿到,通过ServletContext的get/setAttribute的方法取得相应的方法和设置相关的属性

Session与Application 都是通过键---值段的保存,setAttribute(name,value); name是String类型,value

是任何类型。

 

利用Application的方法实现网站的计数:public class TestServletContext extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  ServletContext application = this.getServletContext();
  PrintWriter pw = resp.getWriter();
  Integer accessCount = (Integer)application.getAttribute("accessCount");
  if(accessCount == null) {
   accessCount = new Integer(0);   
  } else accessCount = new Integer(accessCount.intValue() + 1);
  
  application.setAttribute("accessCount", accessCount);
  pw.println("accessCount:" + accessCount.intValue());
  
  
 }

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值