常用API
String getld() 获取 Session的id
long getCreationTime() 获取 Session被创建时间
long getLastAccessedTime () 返回 Session最后活跃的时
boolean isNew() 该Session是否为新的
ServletContext getServletContext () 获取 ServletContext对象void setMaxInactiveInterval(int var1) 设置 Session 超时时间
int getMaxInactivelnterval() 获取 Session 超时时间
Object getAttribute(String var1) 获取 Session 属性
void setAttribute(String var1, Object var2) 设置 Session属性
void removeAttribute(String var1) 移除Session属性
Enumeration getAttributeNames() 获取Session所有的属性名
void invalidate() 销毁该 Session
示例:
1.实体类
public class user {
private string name;
private string email;
public user(){}
//get and set
}
2. HttpSession中存入数据
@Override
protected vold docet(uttpservletRequest req, HttpservletResponse resp)
throus ServletException, IOException [
//向HttpSession中存入数据
HttpSession session = req.getsession();
session.setAttribute("user", new User("Jack","jack@126.com"));
resp.sendRedirect("index.jsp");
}
3.HttpSession中取出数据
@override
protected void docet(HttpservletRequest req, HttpservletResponse resp)
throws servletException, IOException [
//从HttpSession中取出数据
HttpSession session = req.getsession();
user user =(user) session.getAttribute("user");
system.out.printin( user );
}
示例中HttpSession存入数据后,使用了重定向。但是数据仍然可以正常取出。这就是HttpSession和 HttpServletRequest作用域的不同。