Java Web -- what is Session and its usage

Posted by chings on Sun, 23 Jan 2022 16:11:01 +0100

1. What is a Session
When a user requests a Web page from an application, the server will create a Session object for each user (browser);

When the user data needs to be saved, the server program can write the user data to the session exclusive to the user browser;

When a user jumps between Web pages of an application, the variables stored in the Session object will not be lost, but will always exist in the whole user Session. By default, this Session will always exist as long as the browser is not closed.

Session can be understood as an abstract concept, that is, session, which is used to record some behaviors and states of a user on our website

Session stores information that needs to maintain its state throughout the user session, such as login information or other information that users need when browsing Web applications.

Session can also refer to the way to save the user state in the background to realize the session. It stores the user state in the memory, database and other media in the background, and then we use the Session ID saved in the requested Cookie to find its corresponding session for the request.

2. Common methods of session

isNew()//Judge whether it is a new Session. It usually appears during the first access
getid()//Get the session ID
getCreationTime()//The time when the current session was created
getLastAccessedTime()//The time of the last visit to this session.
setAttribute()//Set the value of Session
getAttribute()//Gets the value of Session
removeAttribute()//Remove the value of Session
invalidate()//Manually unregister Session
 Copy code

3. Some usage of session
1. Implement Session
package com.cheng.session;

import com.cheng.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemon01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve the problem of garbled code
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //Get session from request
        HttpSession session = req.getSession();

        //Add data to session
        session.setAttribute("name","Wan Li Gu Yicheng");

        //Get the session ID
        String id = session.getId();

        //Judge whether the session is newly created
        if (session.isNew()){
            resp.getWriter().write("session Created successfully,sessionID by"+id);
        }else{
            resp.getWriter().write("session Already exists in the server, sessionID Is:"+id);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Copy code

Register Servlet

 <servlet>
        <servlet-name>SessionDemon01</servlet-name>
        <servlet-class>com.cheng.session.SessionDemon01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemon01</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
Copy code

Start server test

First visit

Re visit and find that the Session has been saved in the server

2. Get the value in Session across servlets
Stored value of Servlet1:

package com.cheng.session;

import com.cheng.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;


public class SessionDemon01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        session.setAttribute("name","Wan Li Gu Yicheng");
        String id = session.getId();
        if (session.isNew()){
            resp.getWriter().write("session Created successfully,sessionID by"+id);
        }else{
            resp.getWriter().write("session Already exists in the server, sessionID Is:"+id);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Copy code
 <servlet>
        <servlet-name>SessionDemon01</servlet-name>
        <servlet-class>com.cheng.session.SessionDemon01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemon01</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
Copy code

Servlet2 fetch value

package com.cheng.session;

import com.cheng.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

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

        HttpSession session = req.getSession();
        //Take out the value through the key
        String name = (String) session.getAttribute("name");
        resp.getWriter().write(name);

    }

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

Copy code
  <servlet>
        <servlet-name>SessionDemon02</servlet-name>
        <servlet-class>com.cheng.session.SessionDemon02</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemon02</servlet-name>
        <url-pattern>/s2</url-pattern>
    </servlet-mapping>
Copy code

Start server test

First run s1, then run s2

3. Get the objects in the Session across servlets
Object class

package com.cheng.pojo;

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Copy code

Servlet1 storage object:

package com.cheng.session;

import com.cheng.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemon01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        session.setAttribute("name",new Person("Wan Li Gu Yicheng",20));
        String id = session.getId();
        if (session.isNew()){
            resp.getWriter().write("session Created successfully,sessionID by"+id);
        }else{
            resp.getWriter().write("session Already exists in the server, sessionID Is:"+id);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Copy code

   <servlet>
        <servlet-name>SessionDemon01</servlet-name>
        <servlet-class>com.cheng.session.SessionDemon01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemon01</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
Copy code

Servlet2 fetch object

package com.cheng.session;

import com.cheng.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

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

        HttpSession session = req.getSession();
        Person person = (Person) session.getAttribute("name");
        System.out.println(person);
        resp.getWriter().write(person.toString());

    }

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

Copy code
  <servlet>
        <servlet-name>SessionDemon02</servlet-name>
        <servlet-class>com.cheng.session.SessionDemon02</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemon02</servlet-name>
        <url-pattern>/s2</url-pattern>
    </servlet-mapping>
Copy code

Start server test

First run s1, then run s2

3. Log off Session
1. Manual logoff
package com.cheng.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemon03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        //Manual logoff
        session.invalidate();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Copy code

2. Automatic logoff
On the web Add in XML

  <session-config>
        <!--Session Failure after one minute-->
        <session-timeout>1</session-timeout>
    </session-config>
Copy code

There are two usage scenarios: if the user clicks close the browser, he will log out manually. If the user does not visit the web page for a certain time, he can log out automatically

4. The difference between session and Cookie
Cookie is to write the user's data to the user's browser, which can save multiple data
Cookies are not very safe. Others can analyze cookies stored locally and cheat cookies
The validity period of the cookie is set when the cookie is generated.
Cookie schematic:

Session is a data structure saved in the server to track the user's status. This data can be saved in clusters, databases and files

Session is to write the user's data into the user's exclusive session, save the server, login information and other important information into the session

If safety is the main consideration, session should be used;

Session is valid on the web Set in XML configuration file

Schematic diagram of Session:

last
If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts

If you think this article is useful to you, please click star: http://github.crmeb.net/u/defu esteem it a favor!

PHP learning manual: https://doc.crmeb.com
Technical exchange forum: https://q.crmeb.com

Topics: Front-end Operation & Maintenance server