如何使用session?

1:使用session存储信息

在servlet中获取session

httpSession session = request.getSession();

写入session

session.setAttribute("name","tom");

读取session

String n = (String)session.getAttribute("name");

2:设置session的有效期

(1).在tomcat的service.xml中定义

<Context path="/livsorder" docBase="/home/httpd/html/livsorder"

        defaultSessionTimeOut="3600" isWARExpanded="true"

        isWARValidated="false" idInvokerEnabled="true"

        idWorkDirPersistent="false"/>

(2).在工程的web.xml中定义

<session-config>

      <session-timeout>30</session-timeout>

</session-config>

(3).通过java代码设定

HttpSession ses = request.getSession();

ses.serMaxInactiveInterval(10);

3.判断Session是否失效

getSession()方法的作用是返回一个Session对象,如果session不存在,则创建一个并返回;而getSession(boolean create)方法当参数值为true是,如果session不存在则创建一个并返回;当参数为false时,如果session不存在则返回null;

可以通过getSession(boolean create)方法的返回值来判断session是否失效,代码如下

if(request.gerSession(false)==null){

     System.out.println("Session has been invalidated!");

}else{

   System.out.printeln("Session is active!");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值