首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Cookie,Session,Application用法及差异

2012-09-09 
Cookie,Session,Application用法及区别一.Cookie首先,Cookie的作用域为:客户端,即客户端可以对其进行本地

Cookie,Session,Application用法及区别
一.Cookie

       首先,Cookie的作用域为:客户端,即客户端可以对其进行本地限制,如:删除或禁用。

       用法:

       Cookie c=new Cookie(“NAME”,name);//NAME为Cookie的名字,name为参数;

       c.setMaxAge(x);//x单位为s秒;

       response.addCookie(c);//把cookie传送至客户端建立cookie;


二.Session

       首先,Session的作用域为当前打开的Browser(在服务器创建),即session随浏览器打开而建立,随浏览器关闭销毁,可用于访问网站时的权限传递,即一次登录就可以访问各个页面。

       用法:以计数器为例

       HttpSession session=request.getSession();//为客户端创建session,其中()空默认为true,也可以填写false,此时如果客户端没有session则不分配session,不可访问

       int count=0;//用于计数的

       if(session.getAttribute(“COUNT”)==null){//先判断有没有COUNT

session.setAttribute(“COUNT”,new Integer(0));//没有则创建一个,COUNT为对象,为其初始化为0

       else{

       count=(Integer)session.getAttribute(“COUNT”);//如果有session则获取COUNT中的值

       count++;//计数加1,用于本次调用

session.setAttribute(“COUNT”,count);//加1后重新存入COUNT,以便下次使用

}



三.Application

       首先,Application作用域为整个网站的所有访问者,例,可以用来实现整站的计数。

       用法:

       与Session很相似,如下:

       ServletContext app=this.getServletContext();

int count=0;

if(app.getAttribute(“COUNT”)==null){

app.setAttribute(“COUNT”,new Integer(0));

else{

       count=(Integer)appgetAttribute(“COUNT”);

       count++;

app.setAttribute(“COUNT”,count);

}即可实现网站访问量的简单统计

热点排行