JavaWeb実戦——前回のアクセス時間を記録する
3752 ワード
Webサイトがクライアントコンピュータに最後にWebサイトにアクセスしたことを示す時間を実現するのを支援します.
package net.wen.cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet(name = "TimeCookieServlet", urlPatterns = "/timeCookie")
public class TimeCookieServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd ,hh mm ss ");
String curdata = sdf.format(new Date());
// cookie ,
curdata = URLEncoder.encode(curdata,"utf-8");
Cookie[] cookies = request.getCookies();
Cookie timeCookie = new Cookie("timeCookie", curdata);
if(cookies!=null)//
{
for (Cookie cookie : cookies) {
if(cookie.getName().equals("timeCookie")){
String value = cookie.getValue();
//
value = URLDecoder.decode(value,"utf-8");
response.getWriter().write(" :"+value);
break;
}
}
}
if(cookies==null){//
response.getWriter().write(" ");
}
timeCookie.setMaxAge(9999);
response.addCookie(timeCookie);
}
}