• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Java Web Learning (7) — session / cookie object / session object / multiple web resources share dat

King Wang

1 月 3, 2022

JavaWeb Study ( 7、 … and )— conversation /Cookie object /Session object / Multiple Web Resources through Session Shared data / How to log off Session

​ Conversation can be simply understood as : Users open a browser , Click on multiple hyperlinks , Access multiple servers web resources , Then close the browser , The whole process is called a conversation . Usually the conversation is Keep it for a long time Of , No matter how many times the user closes the browser , This conversation has to exist . Each user is in the process of using the browser to talk with the server , It’s inevitable that each will generate some data , The program wants to find a way to save this data for each user .

​ that , How can the client and server save the data ?Java Two technologies have evolved :Session and Cookie.

01 Cookie

Cookie yes Client technology , Server pass Response Put each user’s data into Cookie To the browser in the form of , The browser stores it in its own memory , When the user uses the browser to access the web Resource time , They will take their own Cookie Go to . The server can go through Request Get the user’s Cookie. such ,web What the resource deals with is the data of each user .

How to create Cookie

//name: Identify the name of the message value: Set the value 
Cookie cookie = new Cookie(String name,String value);

How the server will Cookie The response is passed back to the client

Response.addCookie(Cookie);

How does the server see what the client carries Cookie

Cookie[] cookies = Request.getCookie();
Cookie.getName();
Cookie.getValue();

Case study : Use cookie Record the last time the user visited

public class CookieTest extends HttpServlet {

// Define a flag bit , The initial value is false, It is used to determine whether the user has visited this for the first time url
boolean flag = false;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

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

// Avoid random code problems :
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// Get the user's Cookie
Cookie[] cookies = request.getCookies();
if (flag){
//flag=true, Indicates that the user is not visiting the url
if (cookies!=null){
// Do you have cookie
for (int i = 0; i < cookies.length ; i++) {

Cookie cookie = cookies[i];
if (cookie.getName().equals("lastLoginTime")){

response.getWriter().println(" For your last time :"+cookie.getValue());
System.out.println(" Refreshed cookie");
}
}
}
}else {
 //flag=false, Indicates that this is the first time the user has visited the url
response.getWriter().println(" This is your first visit to the page ");
}
// Build a cookie, And put this cookie Send to client 
response.addCookie(new Cookie("lastLoginTime",System.currentTimeMillis()+""));
// take flag Set as true, When the user visits the url when , Will go directly to read cookie The logic of 
flag = true;
}
}

matters needing attention

  1. One Cookie only Can be identified A message , it At least Contains a name that identifies the information (NAME) And settings (VALUE).
  2. One WEB Site You can give one WEB Browser send Multiple Cookie, One WEB Browsers can also store Multiple WEB Site Provided Cookie.
  3. Browsers are generally only allowed to store 300 individual Cookie, Each site most Deposit 20 individual Cookie, Every Cookie Of Size limit by 4KB.
  4. If you create a cookie, And send it to the browser , By default it is a session level cookie( It is stored in the browser’s memory ), After the user exits the browser, it is deleted . If you want the browser to cookie Stored on disk , You need to use maxAge, And give a time in seconds . Set the maximum age limit to 0 Command the browser to delete the cookie.

02 Session

Session yes Server side technology , By default , A browser Monopoly One session object . therefore , When you need to save user data , The server program can write user data to the exclusive of the user browser session in , When a user uses a browser to access other programs , Other programs can be downloaded from the user’s session Take out the user’s data , Serving users . It can be loosely understood as , A user can use a Session Visit multiple Web resources , And each Web Resources can be accessed through Session Read saved user data .

Session Realization principle : Server creation session After coming out , Will be able to session Of id Number , With cookie Write back to the client in the form of , such , As long as the client’s browser is not off , To access the server again , I’ll take it with me session Of id No , Server pass Identify the client browser session_id, It will use the corresponding in memory session To serve .

in fact , As soon as the client connects to the server , The server will Automatically generate Session,Session You can pass data in a session ( That is, multiple programs pass through session get data ), If Server restart , Stored in session The data in will The loss of .

How to get Session object

// Use request Object's getSession() obtain session, If session If it doesn't exist, create a
HttpSession session = request.getSession();
// obtain session Of Id
String sessionId = session.getId();
// Judge session Is it newly created
if (session.isNew()) {
response.getWriter().print("session Create success ,session Of id yes :"+sessionId);
}else {
response.getWriter().print(" The server already exists session,session Of id yes :"+sessionId);
}
  • Case study : Multiple Web Resources through Session Shared data
public class SessionTest01 extends HttpServlet {

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

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

req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
HttpSession session = req.getSession();
String id = session.getId();
resp.getWriter().println("<h3> To obtain a sessionId:</h3>"+id);
String name = "Curry";
session.setAttribute("username",name);
resp.getWriter().println("<h3> At present session Set a user name :</h3>"+name);
}
}
public class SessionTest02 extends HttpServlet {

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

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

req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
String username = (String) req.getSession().getAttribute("username");
resp.getWriter().println("<h3> from session The user name obtained in is :</h3>"+username);
}
}

Running results :
 Insert picture description here
 Insert picture description here

  • How to log off Session?

    session Object default 30 Minutes are not used , The server will automatically destroy session

    There are two ways to log out Session:

    • It needs to be set manually in the program Session When the failure , adopt invalidate(); Cancel current Session.
    request.getSession().invalidate();
    
    • stay web.xml Configuration in file session The expiration time of :
    <!-- Set up Session Effective time of : In minutes -->
    <session-config>
    <session-timeout>15</session-timeout>
    </session-config>
    

03 Session and Cookie The difference between

Cookie It is to write the user’s data to the user’s browser , Belong to Client technology .

Session Write user data to user exclusive session in , Belong to Server technology .

Session Objects are created by the server , Developers can call request Object’s getSession Method to get session object .


发表回复