Session的使用

常用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作用域的不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值