https://howtodoinjava.com/tomcat/a-birds-eye-view-on-how-web-servers-work/

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.

Table of Contents: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 HTTP protocol. 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 and NetDynamics, which eventually all merged into JSP (java server pages), which we still use in most applications development today.

web server application server

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 server servlet 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

Lazy Loaded Servlet1Lazy Loaded Servlet

Eager loading servlet

Eagerly Loaded Servlet1Eagerly Loaded 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

Existing session

New 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.

thread-safety

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 !!

转载于:https://www.cnblogs.com/davidwang456/articles/10297526.html

How web servers work?相关推荐

  1. Java web servers 间是如何实现 session 同步的

     Java web servers 间是如何实现 session 同步的 有一个多月的时间没有更新博客了,今天终于忙里偷闲,可以把近期的收获总结一下. 本文是关于Java web servers 之间 ...

  2. .NET大型Web站点StackOverflow架构分析

    自从2009年8月发布了第一篇关于"Stack Overflow 架构"方面的文章,Stack Overflow已经发生了很大的变化.那篇文章更多关注的是Stack Overflo ...

  3. Web安全学习笔记之HTTP协议

    HTTP是一个应用层协议,主要用于Web开发,通常由HTTP客户端发起一个请求,创建一个到服务器指定端口(默认是80端口)的TCP连接.HTTP服务器则在那个端口监听客户端的请求.一旦收到请求,服务器 ...

  4. web操作系统开发的_哪种操作系统更适合Web开发

    web操作系统开发的 If you're new to web development and are in the market for a new laptop, you might be won ...

  5. 系统在此应用程序堆栈溢出_从部署我的第一个完整堆栈Web应用程序中学到的经验教训...

    系统在此应用程序堆栈溢出 by Will Abramson 威尔·艾布拉姆森(Will Abramson) 从部署我的第一个完整堆栈Web应用程序中学到的经验教训 (Lessons learned f ...

  6. Understanding Web Internals--The flow of Messages

    为什么80%的码农都做不了架构师?>>>    HTTP messages are the blocks of data sent between HTTP applications ...

  7. JAMstack简介:现代Web的体系结构

    I'm sure you've come across the word JAMstack before but you might not have understood what it reall ...

  8. 知识图谱开发实战案例剖析_我从剖析Web开发人员路线图中学到的知识

    知识图谱开发实战案例剖析 by Nicole Archambault 妮可·阿坎巴特(Nicole Archambault) 我从剖析Web开发人员路线图中学到的知识 (What I learned ...

  9. [转]Best Practices for Speeding Up Your Web Site

    本文转自:http://developer.yahoo.com/performance/rules.html#minify The Exceptional Performance team has i ...

最新文章

  1. 修改bootstrap modal模态框的宽度
  2. 【阿里妈妈数据科学系列】第一篇:认识在线实验
  3. 用ul li实现边框重合并附带鼠标经过效果
  4. mysql blob取值_MySQL 数据类型:
  5. hdu4027Can you answer these queries?
  6. JavaScript高级程序设计--01
  7. HDU-2448 Mining Station on the Sea
  8. idea打开linux命令行,在IDEA中使用Linux命令的操作方法
  9. 2021重庆对口高职高考成绩查询,重庆市2021年高职分类考试成绩明日放榜
  10. 文件不混淆_Python代码保护 | pyc 混淆从入门到工具实现
  11. BZOJ1666: [Usaco2006 Oct]Another Cow Number Game 奶牛的数字游戏
  12. 转 可以word ,excel ,pdf ,ppt 导入和导出的思维导图
  13. 基于LM331的频率电压转换电路
  14. Photoshop利用快速蒙版抠图方法
  15. 阿里字体图标库iconfont的使用详解
  16. php mip,php批量清除MIP缓存
  17. 深度学习的过拟合与欠拟合问题的介绍与解决方案
  18. 详细解读《个人所得税专项附加扣除暂行办法》
  19. 凸多面体的表示-H-representation和V-representation
  20. .NET Reflector Crack,用于探索和导航反编译代码

热门文章

  1. 测试isEmpty null 方法
  2. hikvision v2.3控件网页demo_昆山UI网页设计师专业培训班 UI设计好就业吗?
  3. dicom多帧转换_Python解析多帧dicom数据详解
  4. linux yum安装mysql5.7_Linux安装MySQL5.7通过yum安装轻松搞定
  5. 巡检水中机器人_海洋与地球学院学子在2020年国际水中机器人大赛中获得佳绩...
  6. linux 时间戳 c语言,c语言中的时间戳和时间格式
  7. java cordova_java – Cordova android后台插件在5分钟后被杀死
  8. php企业站数据表,php – 创建一个站点来查询表的数据库
  9. json 反射java 实体_Java 将JSON反射到实体类
  10. numpy.tile 阵列