search
HomeJavajavaTutorialDetailed explanation of Java servlet graphic code on the working principle of session

This article mainly introduces the working principle of servlet session. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look

To understand the underlying working principle of Session. Let’s first look at the situation where the same browser accesses multiple web resources during a session. It can be roughly divided into the following steps:

1. The browser accesses a certain Servlet. , at this time, if the server wants to obtain the Session object from the request object (the first acquisition is also created), then the server will create an id for this Session object: JSESSIONID

2, and at the same time, the browser During the response process, this Session will send the id JSESSIONID back to the client browser in the form of a cookie. Remember, the cookie server does not have a valid time set at this time, so it is stored in the browser's cache, not in the hard disk file.

3. When the user continues to access other Servlets during this session, the Servlet will obtain the Session object from the request object. Note that obtaining the Session object at this time is a request sent from the browser. Query whether there is a cookie named JSESSIONID. If there is, then the Session does not need to be created again, but directly queries the Session with the same JSESSIONID value in the server. In other words, the data that previously existed in the Session can be obtained.

In summary, Session is based on Cookie.

(Note: Cookies are not omnipotent. Session first relies on cookies, but sometimes cookies cannot be used. At this time, Session will check whether the URL address sent by the request has JSESSIONID.)

Session’s hidden cookies, we can do a small experiment to verify it. Create two Servlets under the [myservlet] web project, named SessionDemo1 and SessionDemo2 respectively:

The code in SessionDemo1 is:


##

   HttpSession session = request.getSession();
   String data = "Message from SessionDemo";
   session.setAttribute("data", data);

The code in SessionDemo2 is:



   HttpSession session = request.getSession();
   System.out.println((String)session.getAttribute("data"));

We are here Open HttpWatch in the browser to access SessionDemo1. Since this is the first time to access the Servlet, check the response from SessionDemo1 to the browser:


The server sends it back to the browser There is a cookie with this JSESSIONID name. At this time, if we access SessionDemo2 in the opened browser, then observe the content of the request packet in HttpWatch and find:


When accessing the server again, the browser will bring this cookie named JSESSIONID to the server. The server uses the JSESSIONID value in this cookie to find the Session previously created for the browser in the server.


If we close the browser, since this cookie does not have "setMaxAge" set, this cookie only exists in the browser's buffer and will be destroyed when the browser is closed. If we want the Session to still exist after closing the browser, we must manually overwrite the Session cookie and set the validity time and effective path of the override cookie.

The value of this cookie, which is the value of JSESSIONID, can be obtained through the getId() method of Session.

1, override valid time:

Note that after the server creates a Session for the browser, it will not be operated by the user. It will be maintained for 30 minutes by default next time (or after the browser is closed). This can be seen from Tomcat's [web.xml] file:

Of course, we can also modify the server's default destruction of no-operation Session from here. time.


Of course, if we do not want to globally set the destruction time of Session in all servers, we can customize and to set.


Note: We can also destroy a Session immediately through the invalidate() method of the Session object.


In this regard, if we want to overwrite a Session cookie and save it in a hard disk file, the cookie validity time we set should not exceed the server's default session-timeout time.


2, overwrite the effective path:

#If we create a Cookie object and do not set "setPath", then the effective path of the Cookie is to create The cookie's program (usually a Servlet), that is, the browser will carry the cookie with it only when this program is accessed. That is really "unconnected", and the Session cannot be used to access other resources of this web application.


Let’s take a look at the effective path of the cookie in the Session created by the server for the browser when the Servlet was accessed for the first time:


可以看到这个服务器默认将JSESSIONID这个cookie的有效路径设置为创建这个Session的web工程根目录。所以我们要覆盖Session中的cookie时也应该设置路径为该web工程根目录。

好,接下来对上面那个Servlet的例子进行改造,我们只需要在SessionDemo1中修改就行,因为这个首次将Session的cookie返回给客户端,修改后代码如下:


   HttpSession session = request.getSession();
   String data = "Message from SessionDemo";
   session.setAttribute("data", data);
     
   Cookie cookie = new Cookie("JSESSIONID", session.getId());
   cookie.setMaxAge(30*60);
   cookie.setPath("/myservlet");
   response.addCookie(cookie);

这样,当我们打开浏览器访问了SessionDemo1之后,就能在存放cookie的目录中找到该cookie,如果我们通过HttpWatch来查看可以看到重名的这个cookie:

虽然JSEESIONID这个cookie重名了,没有关系,因为其值都是一样的,并且如果我们将浏览器关闭后,没有设置cookie有效时间的(也是原先Session发来的)cookie将不复存在(存在浏览器缓存中,浏览器关闭就被销毁),这时重新打开一个浏览器,再去访问SessionDemo2依然能获取到原来Session中保存的内容:

注意,这是另外打开浏览器窗口访问的SessionDemo2!!另附:

通过这里我们可以看到,我们人为地将原先Session定义的cookie给替换了,而Session并不知道,只要能获得“JSESSIONID”这个cookie,它就认为cookie是存在的,可以从这个cookie中id值获取以前保存的信息,因此我们实现了一台主机共享一个Session,此时,当浏览器关闭,或者说结束一个会话后,依然能获取Session来获取之前保存的数据。

The above is the detailed content of Detailed explanation of Java servlet graphic code on the working principle of session. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool