java httpsession读写_JavaWeb学习笔记-使用HttpSession对象跟踪会话

使用HttpSession接口开发的步骤:

1.获取HttpSession对象

2.对HttpSession对象进行读写

3.手工终止HttpSession,或者自动终止

常用方法:

getId():返回包含分配给这个会话的唯一表示的字符串。在使用URL改写以及标识会话时比较有用

setAttribute():使用指定的名称将对象绑定到这个会话。(setValue()方法)

getAttribution():返回绑定到此会话的对象。(getValue()方法)

invalide():终止当前会话

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//获取会话对象

HttpSession session = request.getSession(true);

response.setContentType("text/html;charset=GB2312");

response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取

PrintWriter out = response.getWriter();

//从会话中获取属性

int count =1;

Integer i = (Integer)session.getAttribute(COUNTER_KEY);

//如果存在以前的数值

if(i!=null){

count=i.intValue()+1;

}

//将属性信息存入会话

session.setAttribute(COUNTER_KEY, new Integer(count));

Date lastAccessed = new Date(session.getLastAccessedTime());

Date sessionCreated = new Date(session.getCreationTime());

DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);

//输出对话信息

out.println("");

out.println("

");

out.println("

会话计数器");

out.println("");

out.println("

");

out.println("你的会话ID:"+session.getId()+"
");

out.println("会话创建时间:"+formatter.format(sessionCreated)+"
");

out.println("会话上次访问时间:"+formatter.format(lastAccessed)+"
");

out.println("会话期间你向页面发起"+count+"次请求");

out.println("

");

out.println("");

out.println("

");

out.println("");

out.println("");

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request,response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request,response);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值