Table of contents
Fourth, the code is as follows
2. If the login is successful, it is judged whether it is the first visit
foreword
Recently, I am learning JavaScript Cookies. I wrote a small exercise after class. The function is to record the time when the user logged in last time. The code has not been optimized and is a bit complicated.
1. What are cookies?
1. A cookie is a piece of data sent by the server to the browser after the browser accesses the server .
2. The browser needs to save this data and should not delete it easily.
3. After that, every time the browser accesses the server, it must bring this piece of data.
Cookies are that simple, and that's what cookies mean in web development. Cookies generally serve two purposes. The first function is to identify the user
2. Demand Analysis
need:
When the user visits for the first time, it displays "Welcome, this is your first visit."
When subsequent users continue to visit, it displays "Welcome back. The time of your last visit is: yyyy-MM-dd HH:mm:ss
Tip 1: You need to use cookies to save the visit time
Tip 2: Create a servlet and make a logical judgment in it to determine whether there is a cookie with the name "lastVisit" you created
Tip 3: Store a cookie every time you visit this The name of the cookie should be consistent
Ideas:
1. Create a cookie to save the visit time (create a cookie, get the value of the cookie)
2. Create a servlet to judge whether it is the first visit Visit
once, create a cookie, the cookie name is: lastVisit
3. When displaying the time, because There are spaces, so encoding and decoding are required
Code: URLEncoder.encode("date","utf-8");
3. How to judge under what circumstances is the first visit and under what circumstances is the nth visit?
(1) The first visit
①Get the current time and display it on the browser
②Create a Cookie object, the time is the value of the cookie, and the name is lastVisit
③Send the cookie to the browser to save
(2) The Nth visit
①Get the cookie Value, take out the cookie named lastVisit
②Get the value of the cookie (the time of the last visit)
③Display the last visit time to the browser
④Update the cookie named lastVisit, set the value to the current time
⑤Send the updated cookie Save to the browser
Fourth, the code is as follows
1. Create a login page
The code is as follows (example):
<%-- Created by IntelliJ IDEA. User: 86155 Date: 2022-09-06 Time: 9:27 To change this template use File | Settings | File Templates. <span style="color: red">${requestScope. <%--Use the el expression to get the value in the field--%> <span>Password: </span><input type="password" name="password"><br> <span>Username:</span><input type="text" name="username"><br> < form action="/CookieDemo1" method="post"> <body> </head> <title>Title</title> <head> <html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> --%> <button type="submit">提交</button> </form> </body> </html>
2. If the login is successful, it is judged whether it is the first visit
The code is as follows (example):
package com.hqyj.j0905.homeWork; /* * 记录用户上次登录的时间 * */ 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.io.PrintWriter; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet("/CookieDemo1") public class CookieDemo1 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse se response) throws ServletException, IOException { //Set encoding style response.setContentType(" text/html;charset=utf-8"); //Get cookie Cookie[] cookies = request.getCookies(); ///Define a flag to indicate whether there is a cookie with the specified name boolean flag = true; String lastVisit = null; //Judge whether the cookie is empty if (cookies != null || cookies.length != 0) { //Traverse for (Cookie cookie : cookies) { //Get the name of the cookie // String name = cookie.getName(); if (cookie.getName().equals("lastVisit")) { //There is a lastVisit cookie, it is already nth visit flag = false; // nth visit // get current time Date date = new Date(); // get formatted date object SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm: ss"); String formatDate = dateFormat.format(date); //Encode the time string String timeNow = URLEncoder.encode(formatDate, "utf-8"); Cookie cookie1 = new Cookie("lastVisit",timeNow); response.addCookie(cookie1); String value = cookie.getValue();//Last visit time //Decode the obtained value String valueDecode = URLEncoder.encode( value, "utf-8"); cookie.setMaxAge(1 * 30 * 24 * 60 * 60); //3. Send the updated cookie to the browser //response.addCookie(cookie); //Get cookie value, time //cookie.setValue(timeNow); //response page PrintWriter writer = response.getWriter(); writer.write("Welcome back, your last visit time is:" + valueDecode); break; } } } //First visit. No cookie, or no cookie named lastVisit if (cookies == null || cookies.length == 0 || flag) { //Set the value of the cookie //Get the string of the current time. Rewrite the value of setting cookie and resend cookie Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatDate = format.format(date); String value = URLEncoder.encode(formatDate, "utf-8"); //2. Create cookie object Cookie cookie1 = new Cookie("lastVisit", value); cookie1.setMaxAge(1 * 30 * 24 * 60 * 60);/ /Set the storage time of the cookie to one month //3. Send the cookie to the browser to save response.addCookie(cookie1); //1. Display the current time to the browser response.getWriter().write("Welcome home, this is your first visit") ; } } }
3. The experimental results are as follows
V. Summary
The above is what I will talk about today. This article only briefly introduces a small exercise of cookies.