session和cookie

session和cookie的区别
  • session是服务端存储,cookie是浏览器端存储
  • Cookie是把用户的数据写给用户的浏览器。
  • Session技术把用户的数据写到用户独占的session中。
  • Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象。
session对象的创建和销毁时机
1)session对象的创建时机
在程序中第一次调用request.getSession()方法时就会创建一个新的Session,可以用isNew()方法来判断Session是不是新创建的
//使用request对象的getSession()获取session,如果session不存在则创建一个 HttpSession session = request.getSession(); //获取session的Id String sessionId = session.getId(); //判断session是不是新创建的 if (session.isNew()) { response.getWriter().print("session创建成功,session的id是:"+sessionId); }else { response.getWriter().print("服务器已经存在session,session的id是:"+sessionId); }
 
2)session对象的销毁时机
session对象默认30分钟没有使用,则服务器会自动销毁session,在web.xml文件中可以手工配置session的失效时间,例如:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 设置Session的有效时间:以分钟为单位--> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
 
session的使用
request.getSession().setAttribute("ossinfoMap",ossinfoMap);
request.getSession().getAttribute("ossinfoMap");
 
session.removeAttribute("sessionname")是清除SESSION里的某个属性. 
session.invalidate()是让SESSION失效.
或许你可以用getAttributeNames来得到所有属性名,然后再removeAttribute 
例如
 public void removeSessionAttributr(HttpServletRequest request){
Enumeration em = request.getSession().getAttributeNames(); //得到session中所有的属性名
while (em.hasMoreElements()) {
  request.gteSession().removeAttribute(em.nextElemet().toString()); //遍历删除session中的值
}
}

posted on 2021-02-25 17:07  媛猿爱逛逛  阅读(48)  评论(0)    收藏  举报

导航