001package edu.pdx.cs410J.servlets; 002 003import javax.servlet.http.Cookie; 004import javax.servlet.http.HttpServlet; 005import javax.servlet.http.HttpServletRequest; 006import javax.servlet.http.HttpServletResponse; 007import java.io.IOException; 008import java.io.PrintWriter; 009import java.time.LocalDateTime; 010import java.time.format.DateTimeFormatter; 011 012/** 013 * This servlet sets cookies on the client's browser to determine when the last 014 * time the page was visited. 015 */ 016public class LastVisitServlet extends HttpServlet { 017 018 private static final String FIRST_VISIT_COOKIE = "firstVisited"; 019 020 private static final String LAST_VISIT_COOKIE = "lastVisited"; 021 022 @Override 023 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 024 PrintWriter pw = response.getWriter(); 025 LocalDateTime now = LocalDateTime.now(); 026 Cookie firstVisitCookie = getCookie(request, FIRST_VISIT_COOKIE); 027 Cookie lastVisitCookie; 028 if (firstVisitCookie == null) { 029 pw.println("<h1>Welcome to the Last Visit servlet</h1>"); 030 pw.println("<p>Check your browser cookies</p>"); 031 firstVisitCookie = createSecureCookie(FIRST_VISIT_COOKIE, now); 032 firstVisitCookie.setComment("This first time you viewed this page"); 033 response.addCookie(firstVisitCookie); 034 035 } else { 036 pw.println("<h1>Welcome back to the Last Visit servlet</h1>"); 037 pw.println("<p>You first visited on " + firstVisitCookie.getValue() + "</p>"); 038 039 lastVisitCookie = getLastVisitCookie(request); 040 pw.println("<p>You were last here on " + lastVisitCookie.getValue() + "</p>"); 041 } 042 043 lastVisitCookie = createSecureCookie(LAST_VISIT_COOKIE, now); 044 response.addCookie(lastVisitCookie); 045 } 046 047 private Cookie createSecureCookie(String name, LocalDateTime now) { 048 Cookie cookie = new Cookie(name, now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 049 cookie.setSecure(true); 050 cookie.setMaxAge(3600); 051 return cookie; 052 } 053 054 private Cookie getLastVisitCookie(HttpServletRequest request) { 055 Cookie cookie = getCookie(request, LAST_VISIT_COOKIE); 056 if (cookie == null) { 057 throw new NullPointerException("Expected to have a " + LAST_VISIT_COOKIE + " cookie"); 058 } 059 return cookie; 060 } 061 062 /** 063 * Returns the cookie from the given request with the given name 064 * 065 * @return <code>null</code> if no cookie with that name exists 066 */ 067 private Cookie getCookie(HttpServletRequest request, String name) { 068 Cookie[] cookies = request.getCookies(); 069 if (cookies == null) { 070 return null; 071 } 072 for (Cookie cookie : cookies) { 073 if (cookie.getName().equals(name)) { 074 return cookie; 075 } 076 } 077 078 return null; 079 } 080}