【Java学习笔记】Cookie Session Application

来源:互联网 发布:一加手机抢购软件 编辑:程序博客网 时间:2024/06/06 05:49

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
原创粉丝点击