1.Cookie对象
cookie是一种会话技术,它用于将会话过程中的数据保存到用户的浏览器中,从而使浏览器和服务器可以更好的地进行数据交互
实现获取Cookie信息并将当前时间发送给客户端:
代码如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
//response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("收到前端请求");
Cookie[] cookies=request.getCookies();
String lastTime=null;
for(int i=0;cookies!=null && i<cookies.length;i++) {
String name=cookies[i].getName();
if("lastAccess".equals(name)) {
lastTime=cookies[i].getValue();
}
}
if(lastTime==null) {
response.getWriter().print("你是首次访问本网站");
}
else {
response.getWriter().print("你上次的访问时间"+lastTime);
}
String time=String.format("%tF<tT", new Date());
Cookie cookie=new Cookie("lastAccess",time);
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);
}
结果:
2.Session对象
Cookie技术可以将用户的信息保存在各自的浏览器中,并且可以在多次请求下实现数据的共享,但是,如果传递的信息比较多,使用Cookie技术显然会增大服务器程序处理的难度,这时,可以使用Session技术
运行结果如下: