Java Web Session Cookie learning notes

Posted by Atari on Sun, 06 Mar 2022 08:01:25 +0100

0 @WebServlet annotation usage

0.1 configuration xml document header

Note: if the annotation is "0-version", please note that the configuration is "version-3"

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1"
         metadata-complete="false">
</web-app>

0.2 code annotation configuration

Add @ WebServlet and mapping path to the class

@WebServlet(urlPatterns = "/s3.do")
public class SessionDemo03 extends HttpServlet {
}

1 session

Session: users open a browser, click many hyperlinks, access multiple Web resources, and close the browser. This process can be called session
Stateful session: a user has visited the server. When he visits the server next time, the server knows that he has visited. It is called stateful session
How to prove the identity of visitors, how to prove that you have been here, and how to prove to the server that the client has been here
cookie: the server gives the client a certificate, and the client can bring the certificate for the next visit
session: the server registers that you have been here. You can match when you come next time

2 two techniques for saving sessions

cookie

  • Client Technology (request, response)

session

  • Server technology. Using this technology, we can save the user's session information. We can put the information or data in the session

In common scenarios, after the website is logged in, you don't need to log in again next time, and the second login is successful by default

3 Cookies

1. Get cookies from the request
2. The server responds to the client

Cookie[] cookies = req.getCookies();//Get Cookies from request
cookie.getName();//Get the name of the cookie
cookie.getValue();//Get the value of the cookie
Cookie cookie1 = new Cookie("time",System.currentTimeMillis()+"");//Create a new cookie
cookie.setMaxAge(24*60*60);//Set cookie validity
resp.addCookie(cookie);//Respond the cookie to the client

cookie, which is usually saved in AppData under the local user directory

  • A cookie can only hold one piece of information
  • A web site can send multiple cookies to the browser and store up to 20 cookies
  • cookie size is limited
  • The browser limit is generally 300 cookie s

delete cookie

  • If the validity period is not set, the browser will automatically become invalid after closing
  • Set the validity period to 0

Encoding and decoding

Cookie namecookie = new Cookie("name", URLEncoder.encode("Li Xiaoyao","UTF-8"));
out.write("Last visited by:"+ URLDecoder.decode(cookie.getValue(),"UTF-8"));

3 Session (key)

What is a Session:

  • The server will create a Session for each user (browser)
  • A Session monopolizes a Session. As long as the browser is not closed, the Session exists
  • After the user logs in, the whole website can be accessed! – > Save user information; Store shopping cart;

The difference between Session and Cookie:

  • Cookie is to write the user's data to the browser, and the browser saves it (multiple can be saved)
  • Session writes the user's data into the user's exclusive session and saves it on the server side (saving important information and reducing the occupation of server resources)
  • The Session object is created by the server by default. It is created when the browser logs in for the first time. After the old Session expires, a new Session is created by default. During client access, the Session ID is carried in the Cookie to access the Session on the server
  • Cookie s can be created by multiple servers

Usage scenario:

  • Save user login information
  • Shopping cart information
  • The data often used in the whole website is saved in Session

Method of using Session

3.1 saving data to Session

public class SessionDemo01 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve garbled code
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //Get Session
        HttpSession session = req.getSession();
        //Save read return
        session.setAttribute("person",new Person("Tomorrow night",21));
        String id = session.getId();
        PrintWriter writer = resp.getWriter();
        if(session.isNew()){
            writer.write("Session Created successfully, ID: "+id);
        }else{
            writer.write("Session Already exists, ID: "+id);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3.2 fetch data from Session

public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        HttpSession session = req.getSession();
        Person person = (Person)session.getAttribute("person");


        PrintWriter writer = resp.getWriter();
        writer.write(person.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3.3 log off Session

@WebServlet(urlPatterns = "/s3.do")
public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("person");

        session.invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3.4 Session session automatically expires

web. Configuration in XML

    <!--set up Session Failure time-->
    <session-config>
        <!--15 Minutes later Session Automatic failure-->
        <session-timeout>15</session-timeout>
    </session-config>

Topics: Java Front-end