Overview of how Web servers work

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

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." "Inmosaic browser (often considered the first graphical web browser) and hyperlink content, evolved the new concept of" Web server ", which is through the http protocol to provide static page content and image services. At that time, most of the content was static, and http 1.0 was just a way to transfer files. But shortly after the Web server provided the cgi function. 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. With the further maturation of the technology, we from Kiva and Netdynamics learned 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. Web Containerin 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 servletWhat is ServletContext? Who is it created by? 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. where do servletrequest and servletresponse 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? The servlet container creates a session when the client accesses the Web app for the first time, or first uses request.getsession () to get httpsession. Generate a long type unique ID (you can use 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 sessionIn 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 multi-threaded 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:
    • 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.
    • }
    • }

Overview of how Web servers work

Related Article

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.