Session management: Cookies and Session

java session management: Cookie and Session

1. What is a session

What here refers to the data transmission between the client (browser) and the server. For example, user login, shopping cart, etc.
Session management is to manage the session data generated during the session between the browser client and the server.
Common conversational techniques
I learned the role of domain objects before, so I can also use the concept of domain objects to find solutions during session management.
There are two main commonly used solutions:
Cookie technology that saves data on the client
Session technology where data is stored on the server side

2.Cookie technology

2.1. What is Cookie

Cookie is a client-side technology. The program writes each user’s data to the user’s respective browser in the form of a cookie. When the user uses the browser to access web resources on the server, they will bring their respective data with them. In this way, the web resources process the data of each user.
Feature is that session data is saved in the browser client

2.2.Cookie technology core API

Cookie class: used to store session data. Commonly used methods are as follows:
1.Construct Cookie object

Cookie(java.lang.String name, java.lang.String value)

2. Set cookies

void setPath(java.lang.String uri): Set the effective access path of the cookie
void setMaxAge(int expiry): Set the validity time of the cookie
void setValue(java.lang.String newValue): Set the value of cookie

3. Send cookies to the browser for storage

void response.addCookie(Cookie cookie): Send cookie

4. The server receives cookies

Cookie[] request.getCookies(): receive cookies

Code example:

/**
 * How to test cookies
 */
@WebServlet(name = "CookieDemo")
public class CookieDemo extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.Create Cookie object
        Cookie cookie = new Cookie("name","eric");

        //2.Set Cookie parameters
        //2.1. Set the effective path of Cookie
        cookie.setPath("/hello");//The default is the address of the web project
        //2.2. Set the validity time of Cookie
        cookie.setMaxAge(20);//This cookie only lives for 20 seconds, starting from the last time the cookie is not adjusted.
        cookie.setMaxAge(-1);//The cookie is stored in the browser memory and will be destroyed when the browser is closed.
        cookie.setMaxAge(0);//Delete the cookie with the same name as the root cookie

        //3.Send data to the browser
        response.addCookie(cookie);

        //4. The server receives the cookie from the browser
        //method 1:
// String name = request.getHeader("cookie");
// System.out.println(name);
        //Method 2:
        Cookie[] cookies = request.getCookies();
        //Note: Judge null, otherwise null pointer
        if(cookies!=null){
            //Traverse
            for(Cookie c:cookies){
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name + "=" + value);
            }
        }else{
            System.out.println("No cookie data received");
        }

    }
}

2.3. Cookie principle

1. The server creates a Cookie object and stores the session data in the Cookie object.

new Cookie(“name”,”value”);

2. The server sends cookie information to the browser

response.addCookie(cookie);
In fact, it hides the response header that sends a set-cookie name.

3. The browser gets the cookie sent by the server and then saves it on the browser side.
4. The browser will bring cookie information with it the next time it accesses the server.

Included in the http request header

5. The server receives the cookie information brought by the browser

request.getCookies();

2.4.Cookie details

1.void setPath(java.lang.String uri): Set the effective access path of Cookie. The effective access path refers to where the effective path of Cookie is stored. Then the browser accesses the server under the effective path. Cookie information will be carried when the
2.void setMaxAge(int expiry): Set the validity time of the cookie
expiry can be a positive integer, a negative integer, and zero
Positive integer: indicates that the cookie data is saved in the browser’s cache to the hard disk, and the value indicates the storage time.
Negative integer: indicates that the cookie data is saved in the browser’s memory and will be lost when the browser closes the cookie.
Zero: means to delete the cookie data with the same name
3. The cookie data type can only store non-Chinese string types. Multiple cookies can be saved, but browsers generally only allow 300 cookies to be stored, and each site can store up to 20 cookies. The size of each cookie is limited to 4KB.

2.5.Cookie case: display the time of the user’s last visit

Function implementation logic:
Save the time in a cookie and call it from the cookie each time you visit
First visit:
1. Get the current time and display it in the browser
2. Create a Cookie object, with time as the cookie value, named: lastTime
3. Send the cookie to the browser for storage
Nth visit:
1. Get the cookie data and take out the cookie named lastTime
2. Get the value of the cookie (last access time)
3. Display the last visit time in the browser
4. Update the cookie named lastTime. The value is set to the current time
5. Send the updated cookie to the browser for storage

Code implementation:

/**
 * Case - the time the user last visited
 */
@WebServlet("/last")
public class HistServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        //Get the current time
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String curTime = format.format(new Date());


        //Get cookies
        Cookie[] cookies = request.getCookies();
        String lastTime = null;
        
        //nth visit
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("lastTime")){
                    //There is a lastTime cookie, which is already the nth visit
                    lastTime = cookie.getValue();//The time of the last visit
                    //nth visit
                    //1. Display the last display time to the browser
                    response.getWriter().write("Welcome back, the time of your last visit was: " + lastTime + ", the current time is: " + curTime);
                    //2.Update cookies
                    cookie.setValue(curTime);
                    cookie.setMaxAge(1*30*24*60*60);
                    //3. Send the updated cookie to the browser
                    response.addCookie(cookie);
                    break;
                }
            }
        }

        /**
         * First visit (no cookie or there is a cookie, but no cookie named lastTime)
         */
        if(cookies==null || lastTime==null){
            //1. Display the current time to the browser
            response.getWriter().write("This is your first time visiting this website, the current time is: " + curTime);
            //2. Create Cookie object
            Cookie cookie = new Cookie("lastTime",curTime);
            cookie.setMaxAge(1*30*24*60*60);//Save for one month
            //3.Send the cookie to the browser and save it
            response.addCookie(cookie);
        }
    }
}

2.6.Cookie case: View the products browsed by the user

Logic diagram

This project has a lot of code, which is placed in different packages according to different functions.
The inverted version of the company domain name + project name + function name
cenyu.hist.entity stores entity objects
cenyu.hist.dao Data Access Object Data Access Object, mainly stores some methods of entity objects (CRUD-create, read, update, delete)
cenyu.hist.servlet stores servlet programs
cenyu.hist.ytil stores tool classes
cenyu.hist.test stores test classes
etc.
Writing order: Entity object–>DAO class–>Servlet program

Code: None

3.Session technology

3.1. What is Session

Session is a server-side technology. Using this technology, the server can create an exclusive Session object for each user’s data at runtime. Since the Session is exclusive to the user’s browser, when the user accesses the server’s web resources, You can put your own data in your own Session. When the user accesses other web resources in the server, the other web resources will take out the data from the user’s respective Session to serve the user.

3.2.Session’s core technology

The Session class is the HttpSession class: used to save session data
1. Create or get the session object
HttpSession getSession() Create a Session object directly
HttpSession getSession(boolean create) receives a Boolean value, and when set to true, creates a new Sessionu object when no object matching the Session number is found. If set to false, null will be returned when no matching Session is found. It is recommended not to use it.
2. Set session object
void setMaxInactiveInterval(int interval): Set the validity time of session
java.lang.String getId(): Get the session number
void invalidate(): Destroy the session object
Session object methods:
1. The setMaxInactiveInterval method automatically recycles the Session object in 30 minutes by default.
2. Use the setMaxInactiveInterval method to modify the destruction time
3. Globally modify the Session default recycling time in the web.xml file

<!-- Modify the session global validity time: minutes -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>

4. Manually destroy the Session object through the invalidate method

3. Save session data to session object
void setAttribute(java.lang.String name, java.lang.Object value): Save data
java.lang.Object getAttribute(java.lang.String name): Get data
void removeAttribute(java.lang.String name): Clear data

4. How to avoid the problem of the browser’s JSESSIONID cookie being lost when the browser is closed:
The solution is to manually send a hard disk protected cookie to the browser
See the case for code:

/**
 * Method to test Session
 */
@WebServlet(name = "SessionServletDemo")
public class SessionServletDemo extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. Create Session object
        HttpSession session = request.getSession();

        //2. Save session data
        session.setAttribute("name","eric");

        //3. Get session data
        String name = (String)session.getAttribute("name");
        System.out.println(name);

        //4.
        //Get the Session id
        System.out.println(session.getId());
        //Modify Session validity time
        session.setMaxInactiveInterval(20);
        //Destroy session
        if (session!=null){
            session.invalidate();
        }
        //Manually send a cookie saved on the hard disk to the browser
        Cookie c = new Cookie("JSESSION", session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);
    }
}

3.3.Session principle

Code interpretation: HttpSession session = request.getSession();
Pseudocode analysis execution process
1. Create a Session object during the first visit and assign a unique ID to the Session object called JSESSIONID.

new HttpSession();

2. Send JSESSIONID as the cookie value to the browser for storage

Cookie cookie = new Cookie(“JSESSIONID”, sessionID);
response.addCookie(cookie);

3. On the second visit, the browser accesses the server with the JSESSIONID cookie.
4. The server gets the JSESSIONID and searches the server’s memory to see if the session object with the corresponding number is stored.
5. If the session object with the corresponding number is found, return the object directly.
6. If the session object with the corresponding number cannot be found, create a new session object and continue with the process of step 1.

Conclusion Find the session object on the server through the cookie value of JSESSION

3.4.Session case: user login effect

Requirements: To achieve the user login effect, if the login is successful, it will display: Welcome back, ×××. If failed, login failed is displayed.
Use Session to distinguish different users. The entire code implementation is divided into three parts, the processing logic after the login form is submitted, the login logic, and the logout logic:
Default login interface. index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Login page</title>
\t
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <form action="/day12/LoginServlet" method="post">
    Username:<input type="text" name="userName"/>
    <br/>
    Password: <input type="text" name="userPwd"/>
    <br/>
    <input type="submit" value="Login"/>
    </form>
  </body>
</html>

Login failure page: fail.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Information prompt page</title>
\t
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <font color='red' size='3'>Dear, your username or password was entered incorrectly! Please re-enter!</font><br/>
    <a href="/day12/login.html">Return to login page</a>
  </body>
</html>

Main processing logic after form submission: IndexServlet.java

/**
 * Logic of user home page
 *
 */
public class IndexServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
\t\t
\t\t
String html = "";
\t\t
/**
* Receive data from the request domain object
*/
/*
String loginName = (String)request.getAttribute("loginName");
*/
\t\t
/**
* 2. On the user homepage, the login is considered successful only if the session is not empty and the specified attributes exist! to access resources.
* Get session data from session domain
*/
//1. Get the session object
HttpSession session = request.getSession(false);
if(session==null){
//If the login is not successful, jump to the login page
response.sendRedirect(request.getContextPath() + "/login.html");
return;
}
//2. Get session data
String loginName = (String)session.getAttribute("loginName");
if(loginName==null){
//If the login is not successful, jump to the login page
response.sendRedirect(request.getContextPath() + "/login.html");
return;
}
\t\t
html = "<html><body>Welcome back," + loginName + ", <a href='" + request.getContextPath() + "/LogoutServlet'>Safe exit</a></body></html> ";
\t\t
\t\t
writer.write(html);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Login processing logic: LoginServlet.java

/**
 * Login processing logic
 *
 */
public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1.Receive parameters
String userName = request.getParameter("userName");
String userPwd = request.getParameter("userPwd");
\t\t
//2.Judgment logic
if("eric".equals(userName)
& amp; & amp; "123456".equals(userPwd)){
\t\t\t//login successful
/**
\t\t\t * analyze:
* context domain object: inappropriate, may overwrite data.
* request domain object: inappropriate, the entire website must use forwarding technology to jump to the page
* session domain object: suitable.
*/
/*
request.setAttribute("loginName", userName);
//request.getRequestDispatcher("/IndexServlet").forward(request, response);
response.sendRedirect(request.getContextPath() + "/IndexServlet");
*/
\t\t\t
/**
* 1. After successful login, save the user data in the session object
*/
//1. Create session object
HttpSession session = request.getSession();
//2. Save the data to the session field
session.setAttribute("loginName", userName);
//3. Jump to the user homepage
response.sendRedirect(request.getContextPath() + "/IndexServlet");
\t\t\t
}else{
\t\t\t//Login failed
//request redirect
response.sendRedirect(request.getContextPath() + "/fail.html");
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Exit processing logic: LogoutServlet.java

/**
 * Exit logic
 *
 */
public class LogoutServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 3. Safe exit:
* Just delete the loginName attribute specified in the session object!
*/
//1. Get the session object
HttpSession session = request.getSession(false);
if(session!=null){
//2.Delete attributes
session.removeAttribute("loginName");
}
\t\t
//2. Return to the login page
response.sendRedirect(request.getContextPath() + "/login.html");
\t\t
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 133503 people are learning the system