`
leonzhx
  • 浏览: 796986 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Zz A birds-eye view on “how web servers work?”

    博客分类:
  • Web
阅读更多

Many times we wonder that how a web container/ web-server (e.g. tomcat or jboss) works? How they handle the incoming http requests coming from all over the world? What are the things which make it happen behind the scene? How java servlet API (i.e. classes like ServletContext, ServletRequest, ServletResponse and Session) fit into picture? These are very important questions/concepts you must know if you are a web-application developer or you aspire to be. In this post, I will try to find out answers for some of above question, if not all. Remain concentrated from here.

Sections in this post:

What are web server, application server and web container?
What are Servlets? How they help?
What is ServletContext? Who creates it?
Where ServletRequest and ServletResponse fits into life cycle?
How Session is managed? Know the cookie?
How thread safety should be ensured?

What are web server, application server and web container?

I will first talk about web servers and application servers. Let me say it in one liner,

“Historically they were different, but these two previously distinct categories slowly merged, and now should be seen as one entity in most of the cases and uses.”

In early days of the Mosaic browser (often described as the first graphical web browser) and hyper-linked content, there evolved a new concept “web server” that served static web page content and images over HTTPprotocol. Simple enough. In these days, most of the content was static, and the HTTP 1.0 protocol was just a way to ship files around. But soon the web servers evolved to have CGI capabilities. It means effectively launching a process on each web request to generate dynamic content. By this time, HTTP protocol also matured and web servers became more sophisticated with additional functionality like caching, security, and session management. As the technology further matured, we got company-specific java-based server-side technology from Kiva andNetDynamics, which eventually all merged into JSP (java server pages), which we still use in most applications development today.


 

This was about web-servers. Now let’s talk about application servers.

In a parallel category, the application servers had evolved and existed for a long time. Some companies delivered products for Unix like Tuxedo (transaction-oriented middleware), TopEnd, Encina that were philosophically derived from Mainframe application management and monitoring environments like IMS and CICS. Most of these products specified “closed” product-specific communications protocols to interconnect “fat” clients to servers. In 90′s, these traditional app server products began to embed basic HTTP communication capability, at first via gateways. And sooner the lines began to blur between these two categories.

By the time, web servers got more and more mature with respect to handling higher loads, more concurrency, and better features; Application servers started delivering more and more HTTP-based communication capability. And all this resulted into very thin line between web-servers and application servers.

At this point the line between “app server” and “web server” is a fuzzy one. But people continue to use the terms differently, as a matter of emphasis.

When someone says “web server” you often think HTTP-centric, web UI oriented applications. When someone says “Application server” you may think “heavier loads, enterprise features, transactions and queuing, multi-channel communication (HTTP + more)”. But mostly it is the same product that serves both sets of requirements now-a-days.

That’s all about web servers and application servers. Now move towards third term i.e. web container.



 Web container, specially in java, should be refer to servlet container. A servlet container is the component of a web server that interacts with java servlets. A web container is responsible for managing the life-cycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights and many more such services. Basically, putting together all above facts, servlet container is the runtime environment where your servlet run and it’s life cycle is maintained.

What are Servlets? How they help?

In java, servlets enable you to write server side components which help in generating dynamic content, based on request. Factually, Servlet is an interface defined in javax.servlet package. It declares three essential methods for the life cycle of a servlet – init(), service(), and destroy(). They are implemented by every servlet(either defined in SDK or user-defined) and are invoked at specific times by the server during it’s life cycle.

Servlet classes are loaded to container by it’s class loader dynamically either through lazy-loading or eager loading. Each request is in its own thread, and a servlet object can serve multiple threads at the same time. When it is no longer being used, it is garbage collected by JVM.

Lazy loading servlet



 

Eager loading servlet


 

What is ServletContext? Who creates it?

When the servlet container starts up, it will deploy and load all web-applications. When a web application gets loaded, the servlet container will create the ServletContext once per application and keep in server’s memory. The webapp’s web.xml will be parsed and every Servlet, Filter and Listener found in web.xml will be created once and kept in server’s memory as well. When the servlet container shuts down, it will unload all web applications and the ServletContext and all Servlet, Filter and Listener instances will be trashed.

As per java docs, ServletContext defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. In the case of a web application marked “distributed” in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won’t be truly global). Use an external resource like a database instead.

Where ServletRequest and ServletResponse fits into life cycle?

The servlet container is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 80. When a client (user with a web-browser) sends a HTTP request, the servlet container 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.

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.

How Session is managed? Know the cookie?

When a client visits the web-app for the first time and/or the HttpSession is to be obtained for the first time by request.getSession(), then the servlet container will create it, generate a long and unique ID (which you can get by session.getId()) and store it in server’s memory. The servlet container will also set a Cookie in 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 web browser and webserver has to adhere), the client (the web browser) is required to send this cookie back in the subsequent requests as long as the cookie is valid. The servlet container will determine every incoming HTTP request header for the presence of the cookie with the name JSESSIONID and use its value to get the associated HttpSession from server’s memory.

The HttpSession lives until it has not been used for more than the time, a setting you can specify in web.xml, which defaults to 30 minutes. So when the client doesn’t visit the web application anymore for over 30 minutes, then the servlet container 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.

Existing Session



 

New Session

 


 

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.

How thread safety should be ensured?

You should now have learned that Servlets and filters are shared among all requests. That’s the nice thing of Java, it’s multi-threaded and different threads (i.e. HTTP requests) can make use of the same instance. It would otherwise have been too expensive to recreate it on every request.

 

 But you should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That’s thread-unsafe! The below example illustrates that:

public class MyServlet extends HttpServlet 
{
    private Object thisIsNOTThreadSafe; //Don't to this
     
    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.
    }
}

Do not do this. It will result in a bug in software.

That’s all on this topic. Stay tuned for more such posts. Better subscribe the email news letter to get the notification in your inbox.

Happy Learning !!

  • 大小: 26.1 KB
  • 大小: 10.8 KB
  • 大小: 12.5 KB
  • 大小: 30 KB
  • 大小: 53.9 KB
  • 大小: 101.2 KB
  • 大小: 28.5 KB
分享到:
评论

相关推荐

    K2980ZZ-TR-E-VB一款N-Channel沟道SOT23的MOSFET晶体管参数介绍与应用说明

    ### K2980ZZ-TR-E-VB N-Channel沟道SOT23 MOSFET晶体管参数介绍与应用说明 #### 概述 K2980ZZ-TR-E-VB是一款高性能N-Channel沟道MOSFET(金属氧化物半导体场效应晶体管),采用SOT23封装形式。这款MOSFET具有低导...

    2SK2980ZZ-TR-E-VB一款SOT23封装N-Channel场效应MOS管

    根据给定的信息,本文将详细解析“2SK2980ZZ-TR-E-VB”这款SOT23封装N-Channel场效应MOS管的关键技术特性与应用领域。 ### 一、产品概述 2SK2980ZZ-TR-E-VB是一款采用SOT23封装的N-Channel沟道MOSFET(金属氧化物...

    ZZ-B-225B.027815.zip

    ZZ-B-225B.027815.zip

    atguigu_springboot2_zz-master.zip

    《SpringBoot2深度解析——基于atguigu_springboot2_zz-master项目实践》 SpringBoot作为现代化Java开发的重要框架,极大地简化了Spring应用的初始搭建以及开发过程。本篇文章将深入探讨基于`atguigu_springboot2_...

    ZZ Fibo Trader - MetaTrader 5EA.zip

    《ZZ Fibo Trader - MetaTrader 5 EA 深度解析》 ZZ Fibo Trader 是一款专为 MetaTrader 5(MT5)平台设计的自动交易专家顾问(EA),其核心在于结合了斐波那契回调线分析和抛物线止损系统,为交易者提供了智能化的...

    DT_ZZ_optimized - MetaTrader 4脚本.zip

    《DT_ZZ_optimized - MetaTrader 4脚本:深入解析与优化技术》 MetaTrader 4(MT4)是一款广泛应用于外汇、期货和股票交易的交易平台,它提供了丰富的技术分析工具和自动化交易功能。在MT4平台中,用户可以编写...

    ZZ_MODIFIED_GEEBINF.ENS

    基于国家标准的endnote的输出样式,适用于学生党论文插入文献参考,较为方便。endnote论文神器。

    zz-zx-Learun.NetCore-master.zip

    ASP.NET Core提供了模型-视图-控制器(MVC)和Web API模式,让开发者可以轻松地构建RESTful服务和Web界面。通过Kestrel服务器,它可以高效地处理HTTP请求,并且可以与其他服务器(如IIS或Nginx)集成以实现更高的...

    ZZ8L-2.5(4)型煤电钻综合保护装置安全操作规程.doc

    ZZ8L-2.5(4)型煤电钻综合保护装置是一种专为煤矿作业设计的安全设备,旨在确保煤电钻操作过程中的人员安全和设备稳定性。该装置集成了多种保护功能,包括漏电保护、短路保护以及必要的电气隔离控制,以防止意外...

    中医大夫助理信息系统 zz-doctor

    《中医大夫助理信息系统 zz-doctor 深度解析》 中医大夫助理信息系统“zz-doctor”是一款基于Android平台的应用程序,旨在为中医医生提供智能化、便捷化的诊疗辅助工具。通过深入剖析这款应用的源码,我们可以了解...

    刀架溜板ZZ027-A).zip

    《刀架溜板ZZ027-A):深入解析三维设计技术在机械工程中的应用》 在现代工业设计中,三维设计技术已经成为不可或缺的一部分。本文将深入探讨标题为“刀架溜板ZZ027-A)”的压缩包文件,该文件包含的产品三维设计图,...

    软件测试-自动化测试-web自动化-教学研究

    ### 软件测试-自动化测试-web自动化-教学研究 #### 知识点解析: **一、自动化测试概述** 自动化测试是一种使用软件工具执行预定义的测试案例来自动验证产品的行为,以确保软件应用程序按预期运行的过程。这种...

    base zz zz zz zz

    base zz zz zz zz zz base zz zz zz zz zz base zz zz zz zz zz base zz zz zz zz zz

    ZZ 颜色折回 - MetaTrader 5脚本.zip

    ZZ 颜色折回是基于简单之字转向指标的。除了基础指标之外,颜色折回分析了波段变化的长度,把长期的波动用蓝色标记二短期的折回用红色标记。

    ZZ-2022010 机器人技术应用赛项赛题.zip

    这个赛题,即“ZZ-2022010 机器人技术应用赛项”,是针对这一目标而设立的竞赛项目。 赛题通常涵盖以下几个核心知识点: 1. **机器人基础知识**:参赛者需要了解机器人的基本构成,包括机械结构、电子元件、传感器...

    3_Level_ZZ_Semafor - MetaTrader 4脚本.zip

    在较大,适中和较小时间周期图表的最大和最小这个指标放置信号旗点上。与Advanced Get类似,但是没有波动计数。

    ZZ-2021030 网络搭建与应用赛项赛卷《网络环境》.pdf

    ZZ-2021030 网络搭建与应用赛项赛卷《网络环境》.pdf

    1-1ZZ1101534.zip

    这款名为"1-1ZZ1101534.zip"的压缩包文件,显然是专门为用户提供了一套精心设计的PPT模板资源。下面将详细介绍这个压缩包中的关键知识点。 首先,压缩包中的"www.1ppt.com.html"可能是一个链接到一个PPT资源网站的...

Global site tag (gtag.js) - Google Analytics