How the Web server works

Source: Internet
Author: User
Tags http cookie session id unique id

How the Web server works

Web Overview of how servers work

Many times we want to knowhow a Web container or Web server (such as Tomcat or JBoss) works. how do they handle HTTP requests from all over the world? What did they do behind the scenes? What role does the Java Servlet API (such as Servletcontext,servletrequest,servletresponse and Session classes) play in? These are important questions or concepts that a Web application developer or a person who wants to be a Web application developer must know. In this article, I will try to give the answers to some of the above questions. Please concentrate!

Article chapters:

    • What are Web servers, application servers, and Web containers?
    • What is a servlet? What role do they have?
    • What is ServletContext? Who is it created by?
    • Where do ServletRequest and servletresponse enter the life cycle?
    • How do I manage a session? Do you know about cookies?
    • How do I ensure thread safety?

What are Web servers, application servers, and Web containers?

I'll discuss the Web server and the application server first. Let me say in a word about:

"In the past they were different, but the two distinct classifications were slowly merged, and now in most cases and in use they can be seen as a whole." ”

At the beginning of the Mosaic browser (often considered the first graphical web browser) and hyperlink content, a new concept of "Web server" was developed, which provides static page content and image services through the HTTP protocol. At that time, most of the content was static, and HTTP 1 was just a way to transfer files. However, shortly after the Web server provided CGI functionality. This means that we can start a process for each Web request to produce dynamic content. Now that the HTTP protocol is ripe and the Web server becomes more complex, there are additional features like caching, security, and session management. As technology matures, we have learned from Kiva and netdynamics the company's proprietary Java-based server-side technology. These technologies are eventually incorporated into the JSPs that we still use in most application development today.

The above is about the Web server. Now let's discuss the application Server .

At the same time, the application server has been in existence and has been developing for a long time. Some companies have developed tuxedo (transactional-oriented middleware),topend,Encina and other products for UNIX, which derive from a host application management and monitoring environment similar to IMS and CICS. Most of these products specify a "closed" product-specific communication protocol to interconnect fat clients ("fat" client) and servers. In the 90 's, these traditional application server products began to embed HTTP communication capabilities and were just beginning to be implemented using gateways. Soon the line between them began to blur.

At the same time, the Web server is becoming more and more mature, can handle the higher load, more concurrency and better features, and the application server begins to add more and more HTTP-based communication functions. All of this leads to a narrower line between the Web server and the application server.

Currently, the line between the application server and the Web server has become blurred. But the two terms were also distinguished as an emphasis on use.

When someone says "Web server", you usually think of it as an HTTP-centric, Web-ui-guided application. When someone says "application server," You might think of "high load, enterprise features, transactions and queues, multichannel communication (HTTP and more protocols)." But it is basically the same product that provides these requirements.

The above is all about the Web server and application server. Now let's take a look at the third term, the Web container.

In Java, a Web container typically refers to a servlet container. A servlet container is a component of a web container that interacts with a Java servlet. The Web container is responsible for managing the life cycle of the servlet, mapping URLs to specific servlets, ensuring that URL requests have the correct access rights, and more similar services. In general,a servlet container is a running environment that is used to run your servlet and maintain its life cycle.

What is a servlet? What role do they have?

In Java,servlets enable you to write server-side components that dynamically generate content on request . In fact, the servlet is an interface defined in the Javax.servlet package. It declares three basic methods--init (), service (), and Destroy () for the life cycle of a servlet. Each servlet implements these methods (defined in the SDK or user-defined) and is called by the server at a specific time in their life cycle.

The ClassLoader automatically loads the servlet class into the container by lazy loading (lazy-loading) or preloading (eager loading) . Each request has its own thread, and a Servlet object can serve multiple threads at the same time. When a Servlet object is no longer being used, it is reclaimed by the JVM as garbage.

Lazy-loaded servlet

Pre-loaded Servlet

What is ServletContext? Who is it created by?

When the servlet container is started, it deploys and loads all of the web apps. When the web app is loaded, the servlet container creates a servlet context (ServletContext) for each app at once and stores it in memory. The servlet container processes the Web. xml file, and once created the servlet, filter, and listener defined in XML, as well as storing them in memory. When the servlet container is closed, it unloads all web apps and ServletContext, and all servlet, filter, and Listner instances are destroyed.

From the Java documentation, ServletContext defines a set of methods that theservlet uses to communicate with its servlet container . For example, to get the MIME type of a file, to forward a request, or to write a log file. in the case of a Web App deployment file (deployment descriptor) labeled "Distributed ," each virtual machine for a web app has a context instance. In this case, the servlet context cannot be treated as a variable that shares global information (because its information is no longer global). You can use external resources instead, such as databases.

ServletRequest and Servletresponse from where to enter the life cycle?

The servlet container is contained in a Web server where the Web server listens for HTTP requests from a specific port, which is typically 80. When a client (user using a Web browser) sends an HTTP request, theservlet container creates a new HttpServletRequest and HttpServletResponse object . and pass them to the method that already created the filter and URL pattern to match the request URL of the servlet instance, all of which use the same thread.

The Request object provides a portal to all the information that gets the HTTP request, such as the requester header and the request entity. The response object provides a convenient way to control and send HTTP responses, such as setting the response header and response entities (typically JSP-generated HTML content). When the HTTP response is committed and ended, both the request and the response object are destroyed.

How do I manage a session? Do you know about cookies?

When a client accesses the Web app for the first time or gets httpsession for the first time using Request.getsession (), the servlet container creates a session that generates a long type unique ID (you can use the Session.getid () to get it) and save it in the server's memory. The servlet container also sets a cookie,cookie name of jsessionid in the HTTP response and the value of the cookie is the unique ID of the session.

Depending on the HTTP cookie specification (a formal web browser and a convention that the Web server must adhere to), the request after the client (Web browser) is returned to the server during the period of the cookie's validity. The Servlet container detects each incoming HTTP request header with a cookie named Jsessionid and uses the value of the cookie to obtain the relevant httpsession from the server content.

HttpSession will survive, unless it is not used for more than a while. You can set this time period in Web. XML, the default time period is 30 minutes . Therefore, if the client has not visited the Web app for more than 30 minutes, the servlet container will destroy the session. Each subsequent request, even with a specific cookie, will never be accessed to the same session. Servletcontainer will create a new session.

The existing session

The new session

In addition, the session cookie at the client has a default time-to-live, which is the same as the browser's run time . Therefore, when the user closes the browser (all tags or windows), the client's session is destroyed. Once you reopen the browser, the cookie associated with the previous session will no longer be sent out. Using Request.getsession again () will return a completely new httpsession and use a new session ID to set the cookie.

How do I ensure thread safety?

You should now know that all requests are in the shared servlet and filter. This is a great feature of Java, it is multithreaded and different threads (that is, HTTP requests) can use the same instance. Otherwise, recreating an entity for each request consumes a lot of resources.

You should also know that you should not use servlet or filter instance variables to hold any request or session-scoped data. This data is shared by all requests from the other session. This is non-thread safe! The following example illustrates the problem:

1

2

3

4

5

6

7

8

9

10

11

12

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 the thread safe.

}

}

Do not do this, which causes the software to get a bug.

All the topics have been finished. Please look forward to more articles. We recommend that you use an e-mail subscription to get notifications for article updates.

Learn to be happy!!

How the Web server works

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.