How do servlets work-Instantiation, sessions, shared variables and multithreading[reproduced]
When the servletcontainer (like Apache Tomcat) starts up, it will deploy and load all webapplications. When a webapplication get loaded, the servletcontainer will create the ServletContext
once and keep in server's memory. The webapp's web.xml
will be parsed and every <servlet>
, <filter>
and <listener>
found in web.xml
, or annotated with respectively @WebServlet
, @WebFilter
and @WebListener
, will be created once and kept in server's memory as well. For all filters, the init()
method will also be invoked immediately. When the servletcontainer shuts down, it will unload all webapplications, invoke the destroy()
of all initialized servlets and filters, and finally the ServletContext
and all Servlet
, Filter
and Listener
instances will be trashed.
When the Servlet
in question has a <servlet><load-on-startup>
or @WebServlet(loadOnStartup)
value greater than 0
, then its init()
method will also immediately be invoked during startup. Those servlets are initialized in the same order as "load-on-startup" value represents, or if they are the same, then the order in the web.xml
or @WebServlet
classloading. Or, if the "load-on-startup" value is absent, then the init()
method will only be invoked on very first HTTP request hitting the servlet in question.
HttpServletRequest and HttpServletResponse
The servletcontainer is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 8080 in development and 80 in production. When a client (user with a webbrowser) sends a HTTP request, the servletcontainer will create new HttpServletRequest
and HttpServletResponse
objects and pass it through the methods of the already-created Filter
and Servlet
instances whose url-pattern
matches the request URL, all in the same thread.
In case of filters, the doFilter()
method will be invoked. When its code calls chain.doFilter(request, response)
, then the request and response will continue to the next filter, or if there is none, hit the servlet. In case of servlets, the service()
method will be invoked, which by default determines based on request.getMethod()
which one of the doXxx()
methods to invoke. If such method is absent on the actual servlet, then it will return HTTP 405 error.
The request object provides access to all information of the HTTP request, such as the request headers and the request body. The response object provides facility to control and send the HTTP response the way you want, such as setting headers and the body (usually with HTML content from a JSP file). When the HTTP response is committed and finished, then both the request and response objects will be trashed (actually, most containers will cleanup the state and recycle the instance for reuse).
HttpSession
When a client visits the webapp for the first time and/or the HttpSession
is to be obtained for the first time by request.getSession()
, then the servletcontainer will create a new HttpSession
object, generate a long and unique ID (which you can get by session.getId()
), and store it in server's memory. The servletcontainer will also set a Cookie
in the Set-Cookie
header of the HTTP response with JSESSIONID
as cookie name and the unique session ID as cookie value.
As per the HTTP cookie specification (a contract a decent webbrowser and webserver has to adhere), the client (the webbrowser) is required to send this cookie back in the subsequent requests in the Cookie
header as long as the cookie is valid (i.e. is not expired and has the right domain and path). Using browser builtin HTTP traffic monitor you can check them (press F12 in Chrome / Firefox23+ / IE9+ and check Net/Network tab). The servletcontainer will determine the Cookie
header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID
and use its value (the session ID) to get the associated HttpSession
from server's memory.
The HttpSession
lives until it has not been used for more than the <session-timeout>
time, a setting you can specify in web.xml
, which defaults to 30 minutes. So when the client doesn't visit the webapp anymore for over 30 minutes, then the servletcontainer will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servletcontainer will create a new one.
On the other hand, the session cookie on the client side has a default lifetime which is as long as the browser instance is running. So when the client closes the browser instance (all tabs/windows), then the session will be trashed at the client side. In a new browser instance the cookie associated with the session won't be sent anymore. A new request.getSession()
would return a brand new HttpSession
and set a cookie with a brand new session ID.
In a nutshell
- The
ServletContext
lives as long as the webapp lives. It's been shared among all requests inall sessions. - The
HttpSession
lives as long as the client is interacting with the webapp with the same browser instance and the session hasn't timed out at the server side yet. It's been shared among all requests in the same session. - The
HttpServletRequest
andHttpServletResponse
lives as long as the client has sent it until the complete response (the webpage) is arrived. It is not being shared elsewhere. - Any
Servlet
,Filter
andListener
lives as long as the webapp lives. They are being shared among all requests in all sessions. - Any
attribute
which you set inServletContext
,HttpServletRequest
andHttpSession
will live as long as the object in question lives. The object itself represents the "scope" in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as anattribute
of closest matching scope.
Threadsafety
That said, your major concern is possibly threadsafety. You should now have learnt that Servlets and filters are shared among all requests. That's the nice thing of Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise have been too expensive to recreate, init()
and destroy()
it on every single request.
But you should also realize that you should never assign any request or session scoped data as aninstance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's threadunsafe! The below example illustrates that:
public class ExampleServlet extends HttpServlet { private Object thisIsNOTThreadSafe; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object thisIsThreadSafe; thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
}
}
From:
http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-sessions-shared-variables-and-multithreadi/3106909#3106909
How do servlets work-Instantiation, sessions, shared variables and multithreading[reproduced]的更多相关文章
- 创建一个dynamics 365 CRM online plugin (八) - 使用Shared Variables 在plugins 之前传递data
CRM 可以实现plugin之前的值传递. 我们可以使用SharedVariables 把值在plugin之间传递 实现plugins之间的传递非常简单,我们只需要用key value pair来配对 ...
- Write thread-safe servlets [reproduced]
If you write Web applications in Java, the servlet is your best friend. Whether you write Java Serve ...
- 【转】Application.mk 文件语法规范
原文网址:http://blog.sina.com.cn/s/blog_4c451e0e0100s6q4.html Application.mk file syntax specification A ...
- 『TensorFlow』分布式训练_其二_单机多GPU并行&GPU模式设定
建议比对『MXNet』第七弹_多GPU并行程序设计 一.tensorflow GPU设置 GPU指定占用 gpu_options = tf.GPUOptions(per_process_gpu_mem ...
- How to choose from Viewstate, SessionState, Cookies and Cache
https://devshop.wordpress.com/2008/04/10/how-to-choose-from-viewstate-sessionstate-cookies-and-cache ...
- Android NDK 学习之Application.mk
Application.mk file syntax specification Introduction: This document describes the syntax of Applica ...
- Freemarker 程序开发
Freemarker 程序开发 现在web开发中,多使用freemarker 来描述页面.通常会使用的macro来定义各种组件,从而达到UI组件的复用.结合使用其它的指定,可快速的描述一个html页面 ...
- Spark——共享变量
Spark执行不少操作时都依赖于闭包函数的调用,此时如果闭包函数使用到了外部变量驱动程序在使用行动操作时传递到集群中各worker节点任务时就会进行一系列操作: 1.驱动程序使将闭包中使用变量封装成对 ...
- theano scan optimization
selected from Theano Doc Optimizing Scan performance Minimizing Scan Usage performan as much of the ...
随机推荐
- ASP.NET Aries 入门开发教程1:框架下载与运行
背景: 鉴于框架的使用者越来越多,文档太少,不少用户反映框架的入门门槛太高. 好吧,再辛苦下,抽时间写教程吧! 步骤1:下载框架源码 开源地址:https://github.com/cyq1162/A ...
- “四核”驱动的“三维”导航 -- 淘宝新UI(需求分析篇)
前言 孔子说:"软件是对客观世界的抽象". 首先声明,这里的"三维导航"和地图没一毛钱关系,"四核驱动"和硬件也没关系,而是为了复杂的应用而 ...
- 用html5的canvas和JavaScript创建一个绘图程序
本文将引导你使用canvas和JavaScript创建一个简单的绘图程序. 创建canvas元素 首先准备容器Canvas元素,接下来所有的事情都会在JavaScript里面. <canvas ...
- zookeeper源码分析之四服务端(单机)处理请求流程
上文: zookeeper源码分析之一服务端启动过程 中,我们介绍了zookeeper服务器的启动过程,其中单机是ZookeeperServer启动,集群使用QuorumPeer启动,那么这次我们分析 ...
- Java compiler level does not match解决方法
从别的地方导入一个项目的时候,经常会遇到eclipse/Myeclipse报Description Resource Path Location Type Java compiler level d ...
- HTML简单入门内容
常用属性: Width=宽度 Height=高度 Size=大小 Color=颜色 Align=布局方向,值包括(top,bottom,left,right,center)上,下,左,右,中. Bor ...
- JQuery的基础和应用
<参考文档> 1.什么是? DOM的作用:提供了一种动态的操作HTML元素的方法. jQuery是一个优秀的js库.用来操作HTML元素的工具. jQuery和DOM ...
- Android 旋转屏幕--处理Activity与AsyncTask的最佳解决方案
一.概述 运行时变更就是设备在运行时发生变化(例如屏幕旋转.键盘可用性及语言).发生这些变化,Android会重启Activity,这时就需要保存activity的状态及与activity相关的任务, ...
- Xamarin Android 应用程序内图标上数字提示
最近在用 Xamarin 做一个 Android 应用,打开应用时,如果有新消息,需要在应用内的 Toolbar 或者首页的图标上显示数字提示.在这里和大家分享一下实现方法,如果你有更新好的实现方法, ...
- Oracle中的commit详解
本文转自 : http://blog.csdn.net/hzhsan/article/details/9719307 它执行的时候,你不会有什么感觉.commit在数据库编程的时候很常用,当你执行DM ...