Conversation Technology
Session: a session contains multiple requests and responses
One session: the browser sends a request to the server resource for the first time, and the session is established until one party is disconnected
Shared data: data is shared among multiple requests within the scope of a session
Client session Technology: cookies
Server side Session Technology: Session
Cookic: client session technology, which saves data to the client
Quick start:
Create Cookie object and bind data new Cookie(String nem,String value)
Send Cookie object response.addCookie(Cookie cookie)
Get the Cookie and get the data Cookie [] request. Getcookies()
Send cookies
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Create a Cookic object Cookie c = new Cookie("msg","hell"); //2. Send Cookic response.addCookie(c); }
Get cookie
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //3. Get Cookic Cookie[] cs = request.getCookies(); //Get data and traverse cookies if (cs!=null){ for (Cookie c : cs) { String name = c.getName(); String value = c.getValue(); System.out.println(name+":"+value); } } }
cookie principle
1. You can send multiple cookies at a time, create multiple cookie objects, and use response to call addcookie method to send cookies
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Create a Cookic object Cookie c1 = new Cookie("msg","hell"); Cookie c2 = new Cookie("name","hello"); //2. Send Cookic response.addCookie(c1); response.addCookie(c2); }
2. By default, when the browser is closed, the cookie data is destroyed
Set the life cycle of the cookie and persist it. setMaxAge(int seconds)
Positive number: writes cookie data to a file on the hard disk. Persistent storage, cookie, lifetime
Negative number: default value, stored in browser memory
Zero: not in the browser and no longer hard disk, but directly deleted
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Create a Cookic object Cookie c = new Cookie("msg","serMaxAge"); //Set cookie lifetime c.setMaxAge(30);//Persist the cookie to the hard disk, and the cookie file will be automatically deleted after 30 seconds //3. Send Cookic response.addCookie(c); }
3. Before tomcat8, Chinese data can not be directly stored in cookie s. After tomcat8, Chinese is supported, but special characters are not supported. It is recommended to use URL encoding for storage and URL decoding for parsing
4. cookie acquisition scope:
a. If multiple projects are deployed in a tomcat server, the cookie s in these web projects cannot be shared by default
If you need to share, you can share through c.setPath("/"), that is, set the path to the root path / of the project
b. cookie sharing among different tomcat servers
setDomain(String path): if the primary domain name is set to be the same, cookie s can be shared among multiple servers
setDomain(".baidu.com"),that tieba.baidu.com and news.baidu.com in cookie Can share
cookie features
1. Cookies store data in the client browser
2. The browser limits the size of a single coolie (4kb) and the total number of cookie s under the same domain name (20)
effect:
Cookies generally store a small amount of less sensitive data
Complete the identification of the client by the server without logging in
Case: record last visit time
1. Access a servlet. If it is the first time, you will be prompted: Hello, welcome to your first visit
2. If it is not your first visit, you will be prompted: Welcome back. The time of your last visit is: display the time string
solve:
1. This can be done using cookie s
2. The Servlet in the server determines whether there is a cookie named lastTime
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Set the message body format of the response, that is, encoding response.setContentType("text/html;charset=utf-8"); //1. Get all cookies Cookie[] cookies = request.getCookies(); boolean glag = false;//Represents no cookie s //2. Traversal cookie array if (cookies != null && cookies.length>0){ for (Cookie cookie : cookies) { //3. Gets the name of the cookie String name = cookie.getName(); //4. Judge whether the name is: lastTime if("lastTime".equals(name)){ glag = true; //This cookie is not the first time to visit //Set the value of the cookie //Get the string of the current time, reset the value of the cookie, and resend the cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MMdd day HH: mm: ss"); String str_date = sdf.format(date); System.out.println("Before coding:"+str_date); //URL encoding str_date = URLEncoder.encode(str_date,"utf-8"); //After coding System.out.println("After coding:"+str_date); //Send cookie s cookie.setValue(str_date); //Set cookie persistence store for resend cookie.setMaxAge(60*60*24*30);//one month response.addCookie(cookie); //Get the value and time of the cookie String value = cookie.getValue(); System.out.println("Before decoding:"+value); //URL decoding value = URLDecoder.decode(value,"utf-8"); System.out.println("After decoding:"+value); response.getWriter().write("<h1>Welcome back. Your last visit was"+value+"</h1>"); break; } } } if (cookies ==null || cookies.length==0 || glag == false){ //No, it represents the first visit //Set the value of the cookie //Get the string of the current time, reset the value of the cookie, and resend the cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MMdd day HH: mm: ss"); String str_date = sdf.format(date); //new a cookie Cookie cookie = new Cookie("lastTime",str_date); System.out.println("Before coding:"+str_date); //URL encoding str_date = URLEncoder.encode(str_date,"utf-8"); //After coding System.out.println("After coding:"+str_date); //Send cookie s cookie.setValue(str_date); //Set cookie persistence store for resend cookie.setMaxAge(60*60*24*30);//one month response.addCookie(cookie); //Get the value and time of the cookie String value = cookie.getValue(); System.out.println("Before decoding:"+value); //URL decoding value = URLDecoder.decode(value,"utf-8"); System.out.println("After decoding:"+value); response.getWriter().write("<h1>Hello, welcome to login for the first time</h1>"); }
JSP: Java Server Pages – > java server pages
You can understand that i have a special page that can define both html and Java code
Used to simplify writing
JSP principle: JSP is essentially a Servlet
JSP script: how JSP defines Java code
1. <% Java% >: defined java code. In the service method, what can be defined in the service method can be defined in the script
2,<%! Java% >: defined java code, member variable of Java class after jsp conversion
3. <% = Java% >: the defined java code will be output to the page. What can be defined in the output statement can be defined in the script
Built in object of JSP
You don't need to get and create objects in jsp pages that can be used directly
jsp has nine built-in objects: request response out
Out: character output stream object, which can output data to the page, similar to response.getWriter(), but no matter where the response is defined, it will be output before out
Case for modifying last access time
<%@ page import="java.util.Date" %> <%@ page import="java.text.SimpleDateFormat" %> <%@ page import="java.net.URLEncoder" %> <%@ page import="java.net.URLDecoder" %><%-- Created by IntelliJ IDEA. User: 64359 Date: 2021/10/19 Time: 18:44 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% //Set the message body format of the response, that is, encoding, but it is not needed here because it has been defined above //response.setContentType("text/html;charset=utf-8"); //1. Get all cookies Cookie[] cookies = request.getCookies(); boolean glag = false;//Represents no cookie s //2. Traversal cookie array if (cookies != null && cookies.length>0){ for (Cookie cookie : cookies) { //3. Gets the name of the cookie String name = cookie.getName(); //4. Judge whether the name is: lastTime if("lastTime".equals(name)){ glag = true; //This cookie is not the first time to visit //Set the value of the cookie //Get the string of the current time, reset the value of the cookie, and resend the cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MMdd day HH: mm: ss"); String str_date = sdf.format(date); System.out.println("Before coding:"+str_date); //URL encoding str_date = URLEncoder.encode(str_date,"utf-8"); //After coding System.out.println("After coding:"+str_date); //Send cookie s cookie.setValue(str_date); //Set cookie persistence store for resend cookie.setMaxAge(60*60*24*30);//one month response.addCookie(cookie); //Get the value and time of the cookie String value = cookie.getValue(); System.out.println("Before decoding:"+value); //URL decoding value = URLDecoder.decode(value,"utf-8"); System.out.println("After decoding:"+value); response.getWriter().write("<h1>Welcome back. Your last visit was"+value+"</h1>"); break; } } } if (cookies ==null || cookies.length==0 || glag == false){ //No, it represents the first visit //Set the value of the cookie //Get the string of the current time, reset the value of the cookie, and resend the cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MMdd day HH: mm: ss"); String str_date = sdf.format(date); //new a cookie Cookie cookie = new Cookie("lastTime",str_date); System.out.println("Before coding:"+str_date); //URL encoding str_date = URLEncoder.encode(str_date,"utf-8"); //After coding System.out.println("After coding:"+str_date); //Send cookie s cookie.setValue(str_date); //Set cookie persistence store for resend cookie.setMaxAge(60*60*24*30);//one month response.addCookie(cookie); //Get the value and time of the cookie String value = cookie.getValue(); System.out.println("Before decoding:"+value); //URL decoding value = URLDecoder.decode(value,"utf-8"); System.out.println("After decoding:"+value); response.getWriter().write("<h1>Hello, welcome to login for the first time</h1>"); } %> </body> </html>
Session: server-side session technology, which shares data between multiple requests of a session and saves the data in the server-side object, HttpSession
quick get start
Get HttpSession object
HttpSession session = request.getSession();
Use the HttpSession object:
1. void setAttribute(String name,Object obj): stores data
2. Object getAttribute(String name): get the value through the key
3. void removeAttribute (String name): remove key value pairs through keys
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Get data using session HttpSession session = request.getSession(); //2. Get data session.setAttribute("msg","hello"); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Using session to share data HttpSession session = request.getSession(); //2. Store data Object msg = session.getAttribute("msg"); System.out.println(msg); }
session principle
The implementation of Session depends on cookies
Session details
1. After the client is shut down, the server does not shut down. The two sessions obtained are not the same session by default
If you need the same, you can create a cookie with the key JSESSIONID, set the maximum survival time, and make the cookie persistent
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Using session to share data HttpSession session = request.getSession(); //It is expected that the session will be the same after the client is closed Cookie c = new Cookie("JSESSIONID",session.getId()); c.setMaxAge(60*60); response.addCookie(c); System.out.println(session); }
2. If the client is not shut down and the server is shut down, the two session s won't be the same
Not the same, but make sure the data is not lost
Session passivation: serialize the session object to the hard disk before the server shuts down normally
Activation of session: after the server starts, convert the session file into a session object in memory
3. Destruction of session
When the server is shut down
The session object calls invalidate()
The default session expiration time is 30 minutes, which can be optionally set in the following code in web.xml
<session-config> <session-time>30</session-time> </session-config>
Characteristics of session
1. Session is used to store the data of multiple requests of a session, which is stored on the server side
2. session can store any type and size of data
The difference between session and cookie
session stores data on the server side and cookie s on the client side
session has no data size limit, and cookie s have
session data is secure, but cookie s are not
case
demand
1. Visit the login page login.jsp with the verification code
2. The user enters the user name, password and verification code
If the user name and password are incorrect, jump to the login page and prompt: the user name and password are incorrect
If the verification code is entered incorrectly, jump to the login page and prompt: the verification code is incorrect
If all inputs are correct, you will jump to the home page success.jsp and display: user name, welcome
loginServlet receives user parameter interface
package cn.zg.servlet; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet( "/loginServlet") public class loginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. Set request encoding request.setCharacterEncoding("utf-8"); //2. Get parameters String username = request.getParameter("username"); String password = request.getParameter("password"); String checkCode = request.getParameter("checkCode"); //3. First obtain the verification code generated by the checkCodeServlet, HttpSession session = request.getSession(); //Object checkCode_session = session.getAttribute("checkCode_session"); //The previous line of code needs to be typed into a string String checkCode_session = (String) session.getAttribute("checkCode_session"); //Delete the verification code, that is, a verification code can only be used once. Delete the verification code stored in the session session.removeAttribute("checkCode_session"); //3. First judge the verification code //The verification code of the picture is a separate request. The generated verification code value ch is saved in the session in the checkcode servlet //Then, the login servlet obtains the verification code from the session and compares it with the entered checkCode //4. Determine whether the verification code is correct if (checkCode_session!= null&&checkCode_session.equalsIgnoreCase(checkCode)){ //Ignore case comparison //The verification code is correct //Determine whether the user name and password are consistent if("Bob".equals(username) && "123".equals(password)){//You need to call Userdao to query the database //Login succeeded //Store user information session.setAttribute("user",username); //Redirect to success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); }else{ //Login failed, store prompt information to request request.setAttribute("login_error","Username or password incorrect "); //Forward to login page request.getRequestDispatcher("/login.jsp").forward(request,response); } }else{ //If the verification code is inconsistent, store the prompt information to request request.setAttribute("checkCode_error","Incorrect verification code"); //Forward to login page request.getRequestDispatcher("/login.jsp").forward(request,response); } } }
checkCodeServlet verification code interface
package cn.zg.servlet; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; @WebServlet("/checkCodeServlet") public class CheckCodeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //First determine the size of the picture int width = 100,height=40; //1. Create an object to store a picture (verification code picture object) in memory //BufferedImage.TYPE_ INT_ Type of RGB picture BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //2. Beautify pictures //2.1 fill background color Graphics g = image.getGraphics();//Brush object g.setColor(Color.pink);//Set background color g.fillRect(0,0,width,height); //2.2 draw border g.setColor(Color.blue); g.drawRect(0,0,width-1,height-1); //Random display verification code String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; //Generate random corner markers Random ran = new Random(); //Receive random verification code characters using StringBuilder StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 4; i++) { int index = ran.nextInt(str.length()); //Get character char ch = str.charAt(index);//Random character sb.append(ch);//Add random verification code characters to StringBuilder //2.3 write verification code g.drawString(ch + "", width / 5 * i, height / 2); } String checkCode_session = sb.toString(); //Store the verification code into the session for data sharing request.getSession().setAttribute("checkCode_session",checkCode_session); //2.4 draw interference line g.setColor(Color.green); //Randomly generated coordinate points for (int i = 0; i < 10; i++) { int x1 = ran.nextInt(width); int x2 = ran.nextInt(width); int y1 = ran.nextInt(height); int y2 = ran.nextInt(height); g.drawLine(x1,x2,y1,y2); } //3. Output pictures to page display ImageIO.write(image,"jpg",response.getOutputStream()); } }
login.jsp login page
<%-- Created by IntelliJ IDEA. User: 64359 Date: 2021/10/19 Time: 22:38 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>login</title> <script> window.onload = function (){ document.getElementById("img").onclick = function (){ this.src = "/day12/checkCodeServlet?time="+new Date().getTime(); } } </script> <style> div{ color: red; } </style> </head> <body> <form action="/day12/loginServlet" method="post"> <table> <tr> <td>user name</td> <td><input type="text" name="username"></td> </tr> <tr> <td>password</td> <td><input type="password" name="password"></td> </tr> <tr> <td>Verification Code</td> <td><input type="text" name="checkCode"></td> </tr> <tr> <td colspan="2"><img id="img" src="/day12/checkCodeServlet" ></td> </tr> <tr> <td colspan="2"><input type="submit" value="Sign in"></td> </tr> </table> </form> <div> <%=request.getAttribute("checkCode_error") ==null? "": request.getAttribute("checkCode_error")%> </div> <div> <%=request.getAttribute("login_error") == null ? " " : request.getAttribute("login_error")%> </div> </body> </html>
success.jsp login success page
<%-- Created by IntelliJ IDEA. User: 64359 Date: 2021/10/19 Time: 23:46 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1><%=request.getSession().getAttribute("user") +"Welcome"%></h1> </body> </html>