


Detailed 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 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:
2, overwrite the effective path:
可以看到这个服务器默认将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!

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

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.

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

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

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.

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

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Small size, syntax highlighting, does not support code prompt function

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
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
