記錄上次訪問時間
import java.util.Date;
import java.text.SimpleDateFormat;
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 LastServlet extends HttpServlet {
/**需求:記錄上次訪問的時間
* 步驟:1.獲取所有的cookie,判斷是否是第一次的訪問
* 2.如果是第一次訪問,那就記錄當前時間,回寫到瀏覽器中;
* 3.如果不是第一次訪問
* 那就是獲取時間,輸出到瀏覽器,記錄當前時間,回寫到瀏覽器。
* 記錄當前的時間,回寫到瀏覽器。
* */
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Cookie [] cookies=request.getCookies();
Cookie cookie=Mycookie.getcookieByName(cookies,"last");
if(cookie==null){
response.getWriter().write("<h3>親,歡迎回來哦!!</h3>");
}else{
String value=cookie.getValue();
response.getWriter().write("<h3>親,又歡迎回來了,上次的時間是" +value+ "!!</h3>");
}
Date date=new Date(); //
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
String sDate=sdf.format(date);
Cookie c=new Cookie("last", sDate);
response.addCookie(c);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}