1. Introduction to Conversational Technology

  A session can be simply understood as: the user opens a browser, clicks multiple hyperlinks, accesses multiple web resources on the server, and then closes the browser. The whole process is called a session.

  In daily life, a series of questions and answers between the call and the hang-up is a conversation. The session process in web applications is similar to the phone call process in life. It refers to a series of requests and responses that occur continuously between a client (browser) and a web server. For example, a user is on a website. The entire shopping process is a session.

  During the call process, both parties to the call will have call records. Similarly, during the interaction between the client and the server, some data will also be generated. For example, users A and B log in to the shopping website respectively, A buys a Nokia mobile phone, and B buys an Ipad. When these two users check out, the web server needs to store the information of users A and B respectively. Both the HttpServletRequest object and the ServletContext object can save data, but neither of these objects is feasible. The specific reasons are as follows:

  (1) When the client requests the web server, for each HTTP request, the web server will create an HttpServletRequest object, which can only save the data transmitted by this request. Since purchase and checkout are two different requests, the data from the previous purchase request will be lost when the checkout request is sent.

  (2) When the ServletContext object is used to save data, since the same Web application shares the same ServletContext object, when the user sends a checkout request, since it is impossible to distinguish which products are purchased by which user, the shopping It is obviously not feasible to settle the goods purchased by all users in the website.

  In order to save the data generated during the session, in the Servlet technology, two objects for saving session data are provided, namely Cookie and Session.

2. Cookie technology

2.1 What are cookies

  Cookie translated into Chinese means small dessert, small biscuits. In HTTP it represents the little dessert that the server sends to the client browser. In fact, a cookie is composed of a key and a value, and is sent to the client browser with the server-side response. Then the client browser saves the cookie and sends the cookie to the server the next time it visits the server.

  A cookie is a key-value pair created by the server and sent to the client in response. The client will save the cookie and mark the source of the cookie (which server's cookie). When the client makes a request to the server, it will include all the server cookies in the request and send it to the server, so that the server can identify the client!

2.2 Cookies and HTTP headers

  Cookies are passed on the client and server side via HTTP request and response headers.

  • The request header, which the client sends to the server;
    Format: Cookie: a=A; b=B; c=C. That is, multiple cookies are left with a semicolon;
  • The response header is sent from the server to the client;

    A Cookie object a Set-Cookie:

    Set-Cookie: a=A

    Set-Cookie: b=B

    Set-Cookie: c=C

  Note: If the server sends duplicate cookies, the original cookies will be overwritten. For example, the cookie sent by the server in the first request of the client is: Set-Cookie: a=A; the second request sent by the server is: Set-Cookie: a=AA, then the client only leaves one cookie, namely: a=AA.

2.3 The life of cookies

  Cookie not only has name and value, but also life. The so-called life is the valid time of the cookie on the client side, and the valid time of the cookie can be set by setMaxAge(int).

  • cookie.setMaxAge(-1): The default value of the maxAge attribute of the cookie is -1, which means it only survives in browser memory. Once the browser window is closed, the cookie disappears.
  • cookie.setMaxAge(60*60): Indicates that the cookie object can survive for 1 hour. When the life is greater than 0, the browser will save the cookie to the hard disk, even if the browser is closed, even if the client computer is restarted, the cookie will survive for 1 hour, and the expired browser will automatically delete the cookie information
  • cookie.setMaxAge(0): cookie life equal to 0 is a special value, which means that the cookie is invalid! That is to say, if the original browser has already saved the cookie, then the cookie can be deleted through setMaxAge(0) of the cookie. This cookie is deleted either in the browser's memory or on the client's hard drive.

2.4 Basic use of cookies

[The server sends a cookie to the client]

  1)Create Cookie : Cookie cookie = new Cookie(String cookieName, String cookieValue);

     Example: Cookie cookie = new Cookie("username","zhangsan"); then the cookie will be sent to the client as a response header:

     Note: Chinese cannot be stored in cookies

  2)Set the persistence time of cookies on the client side : cookie.setMaxAge(int seconds); --- time seconds

     Note: If the persistence time is not set, the cookie will be stored in the browser's memory, and the cookie information will be destroyed when the browser is closed (session-level cookies). If the persistence time is set, the cookie information will be persisted to the browser's disk file. inside.

  3)Set the carrying path of the cookie : cookie.setPath(String path);

        Note: If the carrying path is not set, the cookie information will carry the cookie information in the path where the web resource that generates the cookie is accessed.

      Example: cookie.setPath("/WEB16");——represents access to any resource in the WEB16 application with a cookie

         cookie.setPath("/WEB16/cookieServlet");——Represents that the cookie information is only carried when accessing the cookieServlet in WEB16

  4)Send a cookie to the client : response.addCookie(Cookie cookie);

  5)Delete the client's cookie : If you want to delete the cookie information that the client has stored, use the cookie with the same name and path with a persistence time of 0 to overwrite it.

[The server receives the cookie carried by the client]

  The cookie information is sent to the server in the form of request headers:

  1) Get all cookies through request: Cookie[] cookies = request.getCookies();

  2) Traverse the cookie array and get the cookie we want by the name of the cookie

for(Cookie cookie : cookies){ if(cookie.getName().equal(cookieName)){ String cookieValue = cookie.getValue(); }}

2.5 Case: Display last access time

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); // Create a Cookie object, named lasttime, and create a Cookie object for the current time, The name is lasttime, and the value is the current time Cookie cookie = new Cookie("lasttime", new Date().toString()); // Set the valid time of the cookie on the client to 1 hour cookie.setMaxAge(60 * 60); / / Add cookies to the response response.addCookie(cookie); // Get the cookies in the request Cookie[] cookies = request.getCookies(); String s ="This is your first visit to this website"; // If there are cookies in the request if (cookies != null) { // loop through the cookies in the request for (Cookie c : cookies) { // if the cookie name is lasttime if (c.getName().equals("lasttime")) { // set ss ="The time of your last visit was:"+ c.getValue(); } } } // print s to the responder response.getWriter().print(s);}

3. Session technology

3.1 What is Session




  上图中,用户甲和乙都调用buyServlet将商品添加到购物车,调用payServlet进行商品结算。由于甲和乙购买商品的过程类似,在此,以用户甲为例进行详细说明。当用户甲访问购物网站时,服务器为甲创建了一个Session对象(相当于购物车)。当甲将Nokia手机添加到购物车时,Nokia手机的信息便存放到了Session对象中。同时,服务器将Session对象的ID属性以Cookie (Set-Cookie: JSESSIONID=111)的形式返回给甲的浏览器。当甲完成购物进行结账时,需要向服务器发送结账请求,这时,浏览器自动在请求消息头中将Cookie (Cookie: JSESSIONID=111)信息回送给服务器,服务器根据ID属性找到为用户甲所创建的Session对象,并将Session对象中所存放的Nokia手机信息取出进行结算。

【总结】:Session技术是将数据存储在服务器端的技术,会为每个客户端都创建一块内存空间存储客户的数据,但客户端需要每次都携带一个标识ID去服务器中寻找属于自己的内存空间。所以说Session的实现是基于Cookie,Session需要借助于Cookie存储客 户的唯一性标识JSESSIONID

3.2 有了Cookie为什么还要Session

  • Cookie是有大小和个数的限制的.Session存到服务器端的技术,没有大小和个数的限制.
  • Cookie相对于Session来讲不安全.

3.3 如何获得Session对象

HttpSession session = request.getSession();

  此方法会获得专属于当前会话的Session对象,如果服务器端没有该会话的Session  对象会创建一个新的Session返回,如果已经有了属于该会话的Session直接将已有的Session返回(实质就是根据JSESSIONID判断该客户端是否在服务器上已经存在session了)

3.4 怎样向session中存取数据


  • void setAttribute(String name, Object value):用来存储一个对象,例如:session.setAttribute(“xxx”, “XXX”),在session中保存了一个域属性,域属性名称为xxx,域属性的值为XXX。请注意,如果多次调用该方法,并且使用相同的name,那么会覆盖上一次的值,这一特性与Map相同;
  • Object getAttribute(String name) : used to get the data in the session, currently it needs to be stored before getting it, for example: String value = (String) session.getAttribute("xxx");, get the domain named xxx Attributes;
  • void removeAttribute(String name) : used to remove the domain attribute in HttpSession. If the domain attribute specified by the parameter name does not exist, this method does nothing;

3.5 The life cycle of the Session object

[Create] : Created when request.getSession() is executed for the first time


  1) When the server (abnormally) shuts down

  2) Session expiration/invalidation (default 30 minutes)

  Question: When does time start to count for 30 minutes? (start timing from not manipulating server-side resources)

  It can be configured in the web.xml of the project


  3) Manually destroy the session: session.invalidate();

【Scope of action】:

  The default is in a session, that is to say, any resource in a session shares a session object

JavaWeb Study Notes (6) - Cookie&Session Related posts

  1. JavaWeb Notes (12)-JSP

    jSP: java server pages1. jsp: java server-side page* This page can define both html tags and java code* to simplify writing and avoid writing all page information in the response.getWriter().write() of the Servl class 2. Jsp principle : a. jsp is essentially a servlet 1. The client browser accesses ...

  2. JavaWeb Study Notes (6) - Cookie&Session

    1. Introduction to Conversational Technology  A session can be simply understood as: the user opens a browser, clicks multiple hyperlinks, accesses multiple web resources on the server, and then closes the browser. The whole process is called a session.  In daily life, a series o ...

  3. JavaWeb Synchronization Study Notes 38, JavaWeb_MVC Case: Switch the underlying storage source through configuration

    JavaWeb_MVC case: switch the underlying storage source through configurationMVC case switching the underlying storage source through configurationMVC case switching the underlying storage source through configuration1. In-depth understanding of interface-oriented programming: call the method of the ...

  4. summary and JAVAWEB study opening (1)

    In a hurry, more than 7 months have passed since the last blog, so I wrote an article summary and started JAVAWEB learning.1. Grab new concepts in English. Changed the way of learning after consulting the big English guys in many ways, learning by memorizing English books and listening to more English recordings, the effect is not bad (when it is really effective, share a wave with garden friends~~~)2. Learn to invest in financial management. How should I put it, I'm not good at meeting people, ...

  5. JavaWeb study notes (15) Hibernate's core API

    1. Configuration: Hibernate configuration objectThe role of the Configuration class is to configure Hibernate and start it. During the startup process of Hibernate, the instance of the Configuration class first locates the location of the mapping document, reads the configuration, and then creates a ...

  6. JavaWeb Study Notes (8) - EL Expression

    An overview of EL expressions  In JSP development, in order to obtain the data stored in the servlet domain object, it is often necessary to write a lot of Java code, which will make the JSP page confusing and difficult to maintain. For this purpose, EL expressions are provided in the JSP2 ...

  7. JavaWeb Study Notes (13)--JSP Introduction and Basic Principles

    1. What is JSPThe full name of JSP is Java Server Pages, which, like Servlet technology, is a technology defined by SUN for developing dynamic web resources.The biggest feature of JSP technology:Writing JSP is like writing HTML. Compared with HTML, HTML can only provide users with static data, while ...

  8. Javaweb study notes 10 4 kinds of scope objects

    response objectconfig configuration object (server configuration information)out output objectpage current jsp page objectexception exception objectFour range objects (small--->large)pageContext JSP page container (configuration object) (this object is also called page object in other books, but do not confuse it with the page object above) (current page is valid)request request object (httpServeletRequest class) (valid for the same request)session session object (httpsession class) (valid fo ...

  9. JavaWeb Notes 014 JdbcTemplate

    Basic use of Jdbc [email protected] void run1(){// To create a connection pool, first use the built-in connection pool DriverManagerDataSource of the Spring framework. dataSource = new DriverManagerDataSource();dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc :mysql:/ ...

  10. JavaWeb study notes (1) Web basic concepts

    1. Basic concepts1. Knowledge of Web developmentStatic Web: Refers to the web interface with the same access content at any time. Dynamic Web: Refers to the web interface whose access content changes over time (generally involving interaction with the database). Static web technology: html/css dynam ...

  11. Javaweb study notes 8 The difference between session and cookie

    The difference between cookie and session:          session cookie Saved location Server ClientSecurity More secure Less secureSaved content Object StringWhether it’s a built-in object. It’s a built-in object. It’s not a built-in object. You nee ...

  12. JavaWeb Notes 02: Multithreading

    Process : the smallest unit of operating system resource allocation Thread : the smallest unit of operating system schedulingMulti-process understanding : A pipeline represents a process. To improve efficiency, use multi-process, that is, add multiple pipelines. Multi-threading understanding : addin ...

  13. JavaWeb Development Practical Guide---Notes

    Seven, note 1> main ----mian main method is wrong, no error is reported when javac is compiled, the error will be reported when it is running, and the main method cannot be found. 2> Semicolon 2.1 The semicolon is missing, and an error is reported during compilation. , Need; 2.2 The semicolon ...

  14. JavaWeb Study Notes (12)-Basic Use of JDBC

    One, JDBC overview1.1 Database driver  The driver concept here is the same as the driver concept you usually hear. For example, for the sound card you usually buy, the network card cannot be directly plugged into the computer. You must install the corresponding driver before you can use th ...

  15. javaweb basic notes (3)

    The core foundation of ServletImplementation process:When the Servlet is executed, the construction method is executed first, then the initialization method is executed, and the doGet or doPost method is executed last;The URL of the action in the form is exactly the same as that of the hyperlink;Ser ...

  16. JavaWeb synchronization study notes fourth, the first Servlet program

    JavaWeb_ The first Servlet programThe first servlet programThe first servlet program1. Servlet container: software environment for running Servlet, JSP, Filter, etc.  1) You can create a Servlet and call the related life cycle methods of the Servlet.  2) JSP, Filter, Listener, Tag...2. Ser ...

Recent Posts

  1. c#-Fluent NHibernate-Mapping CultureInfo object?

    I have a class like this:public class User { public CultureInfo Culture {get;set;} }My mapping class is like this:public class UserMap: ClassMap{ public UserMap() { ?? } }I want to use this user cultural information as a cultural string (such as"en-US") to keep it consistent with the database. For N...

  2. Python NameError: The name'self' is not defined. Why?

    At the top:import pygame, sys from pygame.sprite import Sprite from pygame.locals import * pygame.init()Part not working:class DetectionBox(Sprite): def __init__(self): Sprite.__init__(self) self.img = pygame.Surface([SCREEN_WIDTH, SCREEN_HEIGHT/4], SRCALPHA, 32).convert_alpha() self.pos = (0, SCREE...

  3. Linear regression python code implementation

    This code reference from: https://github.com/lawlite19/MachineLearning_Python#%E4%B8%80%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92 First, the linear regression formula: y = X*W + b where X is a data set with m rows and n columns, m represents the number of samples, and n represents the data dimension...

  4. android-How to get the .apk file of the application programmatically

    I want to create an application with the following functions. It should save its .apk file to SD card. Imagine that I have a button. Click it I have to save the application’s .apk file.Solution:It's easy to do this...> First you get all the installed apps > For each one, get the common source ...

  5. java (you need to understand polymorphism first)

    Polymorphism: Generally speaking, in general, the same form, different performance. Too long to watch the series: The so-called polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference var...

  6. javascript – angular2 spring-boot project structure

    I have a new angular2 project, which is built using the standard file structure described in the quickstart. I am trying to build an API gateway and use spring-boot host for my application, but I cannot configure the startup to be in my project Use the /dist directory to create the generated source....

  7. java-the context path in the URI of the static resource, do I really need to specify it?

    I have a simple web application webapp static images -a.gif pages -test.html WEB-INF pages -test.jsp In test.html, there is The problem is that before I change the uri to, the image does not show But I load test.html on the URI http://server/web app name/static/pages/test...

  8. php curl Japanese output garbled

    Please consider the following URL: click here Japanese characters have some encodings. The Firefox browser on my computer can automatically detect and display the characters. On the other hand, for Chrome, I have to manually change the encoding to "Shift_JIS" to see Japanese characters. ...

  9. Record: JAVA abstract classes, interfaces, polymorphism

    JAVA abstract classes, interfaces, polymorphism 1. Polymorphism definition Polymorphism is the ability to have multiple different manifestations or forms of the same behavior. (Polymorphism is the same interface, using different instances to perform different operations) ...

  10. Rails 3.1 with Flot concise Javascript

    all,I am using the Flot graph library in a Rails application. I currently have a page that works as expected, but all the javascript used to put the flot graphs together is inlined in my"view".html.erb file.Is there an easy way to move the static part of javascript to an external file, generate dyna...