JavaWeb—cookie与Session

Technical Session

What is the conversation: the user to open a browser, click multiple hyperlinks to access multiple web server resources, then close the browser, the whole process is called a session. And make phone calls like a telephone receiver, start a conversation, hang up the phone, to end the session.
Session technology to solve a problem: to maintain each client's own data, each user is using a browser and server during a session, each will inevitably produce some of the data, the program to find a way to save the data for each user.

cookie

The information stored in the user's browser among

  • Create a Cookie
Cookie cookie = new Cookie(String cookieName,String cookieValue);

cookie header sent as a response to the client, Cookie can store non-Chinese character string.

  • Sends a cookie to the client
response.addCookie(cookie名称)
  • Cookie default storage time
    default cookie session-level, open the browser, close the browser to a session, if you do not set the persistence time, cookie will be stored in the browser's memory, close the browser cookie information destroyed.
  • Cookie settings stored in the client's time
cookie.setMaxAge(int seconds);

Time set for seconds, if you set the persistence time, cookie information will be persisted to the browser's disk file, expired automatically deleted.

  • Set Cookie Path of carrying
    If an object is created Cookie Path property is not set, then the Cookie is only valid for the current access path and its subdirectories.
cookie.setPath(String path);
//对整个站点有效
cookie.setPath("/");
  • Delete Cookie
    If you want to remove the client's cookie information already stored, using the persistence time of the same name with the path to be covered as a cookie 0.
  • How to get the client server carries cookie
    through the Request object getCookies () method, it is to get all of the cookie, to traverse, to find that one of their own name.
package org.youyuan.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/Servlet8")
public class Servlet8 extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("name","youyuan");
        response.addCookie(cookie);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie1 : cookies) {
            String name = cookie1.getName();
            String value = cookie1.getValue();
            System.out.println(name+"---->"+value);
        }
    }
}

Displays the time the user last visited

@WebServlet("/Servlet9")
public class Servlet9 extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        Date date = new Date();
        String time = null;
        /*这里的时间dd与hh之间一定不能用空格
        * 由于tomcat的版本比较高,所以在addCookie时是不能使用空格的 而在ASCII码中32对应的就是空格
        * 加一个-*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss");
        String format = simpleDateFormat.format(date);

        Cookie cookie = new Cookie("lastTime",format);
        response.addCookie(cookie);

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie1 : cookies) {
                if (cookie1.getName().equals("lastTime")) {
                    time = cookie1.getValue();
                }
            }
        }
        if (time != null){
            response.getWriter().write("当前时间为:"+time);
        }else {
            response.getWriter().write("您是首次登录");
        }
    }
}

session

  • Introduction session: Session technology is server side technology, will create a memory space to store all customer data, the client needs to always carry an identification ID to the server to find their own memory space to store data for each client, Session requires unique identification by means of SESSIONID Cookie storage customers.

  • How Session data do exist in which a servlet, remove the original data stored in other servlet them?
    Each time a user accesses the server, the user will assign himself a corresponding storage space, storage space and created a number we call SessionID, first visit, will sessionID written in the form of corresponding Cookie browser when is next time visit, will carry sessionID, find the storage space had created out of data storage space corresponding to them.

  • Learn how to get the Session object

 HttpSession session = request.getSession();

Access to post Session object for the current session, if there is no server-side Session object for the session, creates a new Session to return, if you already have the session Session belonging directly to the existing Session returned, according to the judge essentially SESSIONID if the client already exists in the session on the server.

  • How to access the data to the session among the
    Session object is a domain object
 HttpSession session = request.getSession();
 session.setAttribute("name","youyuan");
 String name = (String) session.getAttribute("name");
 System.out.println(name);
 session.removeAttribute("name");
  • session life cycle
  1. Creating
    created when the first execution request.getSession ()
  2. Destruction
    server shut down when
    the session expired / invalid (default 30 minutes), it is at the end of timing from the last operation.
    Manual destruction
session.invalidate();
  • Scope
    default in one session, that is to say, a session in a session object to any public resources

JsessioID persistence

By default, the first time get the session object, will help you create a session, you can get the Session's ID, it will automatically write the cookie among the id.
Problems:
storing some data first access sevlet1, direct access to data in the second servlet which can be taken directly.
The browser is closed, directly to the second fetch data among servlet, fail to find the data.
The reason:
because the time of the visit with the requirements jsessionID, because the default storage cookie is session-level, close your browser, no. So open the browser again. When accessing resources, no jsessionID. Will create a new session. Will fail to get the data.
Solution:
When writing data to manually go to the sessionID cookie wrote them, write, set the persistence time, attention, and it must be the key value automatically generated key value is the same.

Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(30*60);
cookie.setPath("/");
response.addCookie(cookie);
Published 25 original articles · won praise 0 · Views 276

Guess you like

Origin blog.csdn.net/qq_42219004/article/details/105326077