Servlet2

package gz.itcast.c_cookie;

 

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

 * 案例-用户上次访问时间

 * @author APPle

 * 阿萨德所

 */

public class HistServlet extends HttpServlet {

 

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");

 

//获取当前时间

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

String curTime = format.format(new Date());

 

 

//取得cookie

Cookie[] cookies = request.getCookies();

String lastTime = null;

if(cookies!=null){

for (Cookie cookie : cookies) {

if(cookie.getName().equals("lastTime")){

//有lastTime的cookie,已经是第n次访问

lastTime = cookie.getValue();//上次访问的时间

//第n次访问

//1.把上次显示时间显示到浏览器

response.getWriter().write("欢迎回来,你上次访问的时间为:"+lastTime+",当前时间为:"+curTime);

//2.更新cookie

cookie.setValue(curTime);

cookie.setMaxAge(1*30*24*60*60);

//3.把更新后的cookie发送到浏览器

response.addCookie(cookie);

break;

}

}

}

 

/**

 * 第一次访问(没有cookie 或 有cookie,但没有名为lastTime的cookie)

 */

if(cookies==null || lastTime==null){

//1.显示当前时间到浏览器

response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime);

//2.创建Cookie对象

Cookie cookie = new Cookie("lastTime",curTime);

cookie.setMaxAge(1*30*24*60*60);//保存一个月

//3.把cookie发送到浏览器保存

response.addCookie(cookie);

}

}

 

}

 

 

// request.getSession(true):若存在会话则返回该会话,否则新建一个会话。

// request.getSession(false):若存在会话则返回该会话,否则返回NULL

// getSession() 等同于 request.getSession(true)

HttpSession session = request.getSession(false);

if (session != null) {

session.invalidate();// 手动销毁

}

System.out.println("销毁成功");

 

//1.创建session对象

HttpSession session = request.getSession();

 

/**

 * 得到session编号

 */

System.out.println("id="+session.getId());

 

/**

 * 修改session的有效时间

 */

//session.setMaxInactiveInterval(20);

 

/**

 * 手动发送一个硬盘保存的cookie给浏览器

 */

Cookie c = new Cookie("JSESSIONID",session.getId());

c.setMaxAge(60*60);

response.addCookie(c);

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值