Servlet case 6: display the user's last access time and servlet's last access
Here is a simple cookie Application
Tell the user that your last access time is: xxxx-xx: xx
Ideas:
When you access the website for the first time, record the current access time (new Date ())
Write the current time to the client in the form of a cookie (response. addCookie)
During the second access, obtain the cookie carried by the client and display it to the user.
Overwrite the last access time
Code implementation:
Package cookie; import java. io. IOException; import java. text. simpleDateFormat; import java. util. 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 LastAccessTimeServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// get the current time and format Date date = new Date (); SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss "); String currentTime = format. format (date); // create a cookie, record the latest access time Cookie cookie = new Cookie ("lastAccessTime", currentTime); // cookie retention time 24 hours cookie. setMaxAge (60*60*24); // Save the cookie response. addCookie (cookie); // obtain the client port Cookie String lastAccessTime = null; Cookie [] cookies = request. getCookies (); if (cookies! = Null) {for (Cookie coo: cookies) {if ("lastAccessTime ". equals (coo. getName () {lastAccessTime = coo. getValue () ;}} response. setContentType ("text/html; charset = UTF-8"); if (lastAccessTime = null) {response. getWriter (). write ("your first access");} else {response. getWriter (). write ("your last access time was:" + lastAccessTime) ;}} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
Pay attention to web. xml configuration
Effect:
First visit:
Second access (refresh ):
Complete