package com.ask.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.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;
//显示用户上次访问的时间;
public class CookieTime extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置字体格式
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//存入当前时间;
Cookie cookie=new Cookie("lastAccessTime", System.currentTimeMillis()+"");
//将cookie交给response对象响应到浏览器中
resp.addCookie(cookie);
PrintWriter out=resp.getWriter();
String time="";
Cookie[] cookies=req.getCookies();
for (Cookie cookie2 : cookies) {
if("lastAccessTime".equals(cookie2.getName())){
time=cookie2.getValue();
long times=Long.parseLong(time);
Date date=new Date(times);
out.print("你当前的访问时间是: "+date);
}
}
}
}
2.web.xml配置文件如下:
<!-- 获得时间 -->
<servlet>
<servlet-name>CookieTime</servlet-name>
<servlet-class>com.ask.cookie.CookieTime</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieTime</servlet-name>
<url-pattern>/CookieTime</url-pattern>
</servlet-mapping>