servlet, servlet container, and other content explained

Source: Internet
Author: User

Reprinted from http://blog.csdn.net/iAm333

For Servlets, servlet containers, and a servlet container-tomcat These concepts are very clear, reproduced under

Before in open source China saw an article, "Beginner Java Web Development, please stay away from the various frameworks, from the Servlet development", feel very good. I felt ashamed to think of myself before having been obsessed with various frameworks. So, read Xinxin Sun's "servlet/jsp in-depth: Tomcat-based Web development", Lin Shinliang's "Jsp&servlet Study notes (second edition)" and some other related information on the Internet, to organize their own understanding of the following.

Web Technology

With the development of Internet technology, Web applications based on HTTP and HTML are growing rapidly. Early Web applications are mainly used to browse static pages such as news, the user requests the static page on the server through the HTTP protocol, after the server's Web server software receives the request, reads the URI marked resources, plus the message sends the hair to the client browser, the browser is responsible for parsing the HTML, the result is rendered Now come out.

However, as time progresses, users are not satisfied with browsing static pages only. The user needs some interaction to get some dynamic results. If server-side software enhancements based on the HTTP protocol are too complex, some extension mechanisms are needed to implement the functionality that the user wants. The Web server extension mechanism used earlier is CGI (Common Gateway Interface, Public Gateway Interface). Using this method, the user clicks a link or enters a URL to access the CGI program, the Web server receives the request, runs the CGI program, processes the user request, and then processes the result and produces a response, which is returned to the Web server, which wraps the response. Returned to the browser in the form of an HTTP response.

The CGI program solves the user's needs to some extent. However, there are some shortcomings, such as the difficulty of writing CGI programs, longer response times, and running in a process mode resulting in limited performance. So in 1997, Sun unveiled the servlet technology as a CGI solution for the Java camp.

Servlet and Servlet containers

Java servlet (Java Server applet) is a Java-based Web component that runs on the server side and is managed by the Servlet container for generating dynamic content. Servlets are platform-independent Java classes that write a servlet that actually writes a Java class according to the servlet specification. The servlet is compiled into a platform-independent bytecode that can be dynamically loaded into a Web server that supports Java technology.

A servlet container, also called a servlet engine, is a part of a Web server or application server that provides network services on top of sent requests and responses, decodes MIME-based requests, and formats MIME-based responses. The servlet has no main method, cannot run independently, it must be deployed to the servlet container, and the methods of the servlet (such as doget () and Dopost ()) are instantiated and invoked by the container. The servlet container embraces and manages servlets throughout the servlet's life cycle. When JSP technology is launched, the container for managing and running servlet/jsp is also known as the Web container.

(note: Commonly used MIME types: text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar,application /octet-stream,application/x-zip)

With a servlet, the user accesses the Servlet,web server by clicking on a link or entering a URL directly into the browser's address bar, rather than handing the request directly to the servlet, but to the servlet container. The servlet container instantiates a servlet, invokes a specific method of the servlet, processes the request, and produces a response. This response is returned by the servlet container to the Web server, which wraps the response and sends it to the Web browser in the form of an HTTP response.

What can a servlet container provide?

We know that servlets need to be managed and run by a servlet container, but why do we do this? The reasons for using the servlet container are:

Communication support: Using the method provided by the container, you can easily let the servlet talk to the Web server without having to build serversocket, listen to a port, create a stream, and so on. The container knows the protocol between itself and the Web server, so your servlet doesn't have to worry about the API between the Web server (such as Apache) and your own web code, just consider how to implement the business logic in the servlet (such as processing an order).
Lifecycle Management: The servlet container controls the life and death of the servlet, which is responsible for loading classes, instantiating and initializing the servlet, invoking the Servlet method, and making the servlet instance garbage-collected, with the servlet container, and you don't need to think too much about resource management.
Multithreading support: The container automatically creates a new Java thread for each servlet request it receives. For the user's request, the thread will end if the servlet has already run the appropriate HTTP service method. This is not to say that you don't have to think about thread safety, but you also have a sync problem, but that can make you less work.
Declarative security: With the servlet container, you can use the XML deployment profile to configure and modify security without having to hard-code it into the Servlet class code.
JSP support: The servlet container is responsible for translating the JSP code into real Java code.

In contrast to CGI programs, Servlets have the following advantages:

A servlet is a single-instance multithreaded operation in which each request runs in a separate thread, while the servlet instance that provides the service has only one.
Servlets are upgradeable and can respond to more requests because the servlet container uses a thread rather than an operating system process, and the thread consumes only limited system resources.
The servlet uses the standard API and is supported by more Web servers.
The servlet is written in the Java language and therefore has all the advantages of the Java programming language, including ease of development and platform independence.
Servlets have access to the Java platform's rich library of classes, making it easier to develop a variety of applications.
The servlet container provides additional functionality to the servlet, such as error handling and security.

Classification of servlet containers

The servlet container can be divided into the following three categories, depending on the servlet container working mode:

1) stand-alone servlet container

When we use a Java-based Web server, the servlet container exists as part of the Web server. However, most Web servers are not Java-based, so there are two types of servlet containers working in the following mode.

2) in-process servlet container

The servlet container consists of the Web server plug-in and the Java container's implementation of the two parts. The Web server plug-in opens a JVM (a Java Virtual machine) in a Web server's internal address space, allowing the Java container to load and run the servlet in this JVM. If a client invokes the servlet's request, the plug-in obtains control of the request and passes it (using JNI technology) to the Java container, which is then referred by the Java container to the servlet for processing. The in-process servlet container is ideal for single-process, multi-threaded servers, providing high speed, but with insufficient scalability.

3) out-of-process servlet container

The servlet container runs in an address space outside the Web server, and it is made up of both the Web server plug-in and the Java container implementation. The Web server plug-in and the Java container (running in the external JVM) communicate using the IPC mechanism (usually TCP/IP). When a request to the servlet arrives, the plug-in obtains control of the request and passes it (using the IPC mechanism) to the Java container. Out-of-process servlet containers respond to customer requests less quickly than in-process servlet containers, but out-of-process containers have better scalability and stability.

Tomcat

To learn servlet technology, you need to have a servlet runtime environment, that is, you need a servlet container, this article uses Tomcat.

Tomcat is a free open source servlet container, a top-of-the-line project of the Apache Software Foundation (Apache Software Foundation) developed by Apache, Sun, and other companies and individuals. With Sun's involvement and support, the latest servlet and JSP specifications are always reflected in Tomcat, and Tomcat 6 supports the latest servlet 2.5 and JSP 2.1 specifications. Because Tomcat technology advanced, stable performance, and free, and thus deeply loved by Java enthusiasts, and has been recognized by some software developers, become the most popular Web server.

Tomcat, like IIS, Apache and other Web servers, has the ability to handle HTML pages, and it is also a servlet and JSP container, and the standalone servlet container is the default mode for Tomcat. However, Tomcat does not have the ability to handle static HTML as well as Apache, and we can integrate Apache with Tomcat, Apache as an HTTP Web server, and Tomcat as a Web container.

The process for the Tomcat server to accept customer requests and respond is as follows:

1) The client (usually the browser) accesses the Web server and sends an HTTP request.
2) After the Web server receives the request, it is passed to the servlet container.
3) The servlet container loads the servlet and, after producing the servlet instance, passes it to the object that represents the request and response.
4) The Servlet instance uses the request object to obtain the client's request information and then handles it accordingly.
5) The servlet instance sends the processing results back to the client through the response object, which is responsible for ensuring that the response is sent out correctly while returning control to the Web server.

Installation and configuration of Tomcat

Install the JDK before you install Tomcat. JDK download and configure a lot of online tutorials, can Baidu or Google. To download tomcat, first access the Tomcat Project URL: http://tomcat.apache.org/, select the version of Tomcat you want to download.

For Windows operating systems, Tomcat provides a download of the executable installer, the "Windows Service Installer" link. Installing Tomcat through the installer will install Tomcat as a service for Windows. However, it is recommended that you download the zip archive to install Tomcat in an uncompressed manner, because the decompression is also applicable to other operating systems (such as Linux systems) and is easier to integrate with other development environments. For beginners, it is also better to learn about Tomcat's startup process.
After the download is complete, unzip the package into the specified directory using the Unzip tool such as WinZip or WinRAR. Then add the directory of the Bin folder under the Tomcat folder in the PATH environment variable, such as D:\apache-tomcat-version \ Bin. This article uses the latest version of apache-tomcat-7.0.33 as of the time this article was written.

Tomcat's directory structure

The Tomcat is installed as shown in directory hierarchy 1.


Figure 1 The use of the Tomcat 7.0.33 directory hierarchy is shown in table 1.
Directory Use
/bin Storing script files to start and close Tomcat
/conf Various configuration files for the Tomcat server, including Server.xml (Tomcat's primary profile), Tomcat-users.xml, and Web. XML configuration Files
/lib Store the jar files that the Tomcat server and all Web applications need to access
/logs Log files that hold Tomcat
/temp Storing temporary files generated by Tomcat runtime
/webapps When publishing a Web application, it is common to place directories and files of Web applications in this directory
/work Tomcat places JSP-generated servlet source files and bytecode files into this directory
Table 1 Tomcat directory structure and its uses

As you can see from table 1, the jar files stored in the Lib directory can be accessed by all Web applications, and if multiple Web applications require access to the same jar file, you can place the jar files in the Tomcat Lib directory. In addition, for the Java Web application that will be introduced later, in its Web-inf directory, you can also create a Lib subdirectory, in the Lib subdirectory can hold a variety of jar files, these jar files are only accessible to the current Web application.

Running Tomcat

In the bin subdirectory of the Tomcat installation directory, There are batch files (files with. bat as the suffix), where Startup.bat is the script file that launches Tomcat, double-click the file with your mouse, if you have previously configured JDK and tomcat (configuration shown in Figure 2, PATH variable and Java_ Home variable), the 3 window will open.


Figure 2 JDK and Tomcat configuration


Figure 3 Tomcat Startup window

Note: If the Startup window shown in 3 does not appear, it is a flash and it proves that JDK and Tomcat are not configured and reconfigured.

Open the browser, enter http://localhost:8080/in the address bar (localhost means the local machine, 8080 is the port number that Tomcat listens to by default), and the Tomcat page shown in 4 appears. If you want to close the Tomcat server, you can double-click the Shutdown.bat file in the Tomcat bin directory with your mouse.


Figure 4 Tomcat default home page

Tomcat Boot Analysis

We use a text editor to open the batch file Startup.bat used to start Tomcat and analyze it. The detailed analysis process is shown in Figure 5.


Figure 5 Startup.bat File analysis

As we can see from the analysis in Figure 5, the Startup.bat script mainly looks at the directory where the current command is located. See if it is in the tomcat\ or tomcat\bin\ directory. and view the arguments that will call the command to Catalina.bat. Finally call the Catalina.bat Start command. The main function of Startup.bat is to invoke the Catalina.bat start command. Therefore, to start Tomcat with the same startup in other directories, you need to set the CATALINA_HOME environment variable. Set the value of the CATALINA_HOME environment variable to the installation directory of Tomcat.

One might wonder why Java_home represents the Java installation directory, but the Tomcat installation directory is not tomcat_home, but is represented by Catalina_home. In fact, before Tomcat 4, Tomcat_home was used to represent the Tomcat installation directory.

After the Startup.bat file is solved, let's take a look at the Catalina.bat file that is really responsible for starting the Tomcat server. Catalina.bat files are long, so the detailed analysis process is shown in Figure 6.







Figure 6 catalina.bat file Analysis

The analysis shows that Catalina.bat is actually calling the Java command to run the Bootstrap class. From the above code, we know that Tomcat is really a pure Java program, all the scripts eventually become the direct use of Java command Execution program, and our ordinary written Java program, no different. Just because the tomcat pattern is too many and requires a variety of parameters (such as Debug,start, etc.), it needs to be executed using a script. In addition, by parsing the Catalina.bat file, we found that it also called a file setclasspath.bat. In the Setclasspath.bat file, it checks to see if the JAVA_HOME environment variable exists and, through Java_home environment variables, finds Java.exe, which is used to start Tomcat. In this file, you also set some other variables that represent standard commands that call Java, and you can analyze the file yourself if you are interested.

The architecture of Tomcat

The Tomcat server is made up of a series of configurable components, the core of which is the Catalina servlet container, which is the top-level container for all other Tomcat components. We can understand the hierarchical relationship between Tomcat components by looking at the Server.xml file in the Conf folder under the Tomcat installation folder. Because server.xml annotations are too many, the special simplification is as follows:

[HTML]View Plaincopy print?
  1. <? xml version= '1.0 ' encoding=' utf-8 '?>
  2. <Server port="8005" shutdown="shutdown">
  3. <Service name="Catalina">
  4. <Connector port="8080" protocol="http/1.1" connectiontimeout= "20000" redirectport= "8443" uriencoding="UTF-8"/>
  5. <Engine name= "Catalina" defaulthost="localhost">
  6. <Host name="localhost">
  7. <Context path= "" docbase="Workdir" reloadable="true"/>
  8. </Host>
  9. </Engine>
  10. </Service>
  11. </Server>


Where Workdir is the path to the project you want to import. Let's take a brief look at the role of each component in the Tomcat server.

(1) Server

The server represents the entire Catalina servlet container. Tomcat provides a default implementation of the server interface, which usually does not need to be implemented by the user itself. In the server container, you can include one or more service components.

(2) Service

A service is an intermediate component that survives within the server and binds one or more connector (Connector) components to a single engine. In server, you can include one or more service components. Service is also rarely customized, and Tomcat provides the default implementation of the service interface, which is both simple and satisfying to use.

(3) Connector

The connector (Connector) handles communication with the client, which is responsible for receiving customer requests and returning response results to the customer. In Tomcat, there are multiple connectors that can be used.

(4) Engine

In Tomcat, each service can contain only one servlet engine. The engine represents a request processing pipeline for a particular service. As a service can have multiple connectors, the engine receives and processes all requests from the connector, returns the response to the appropriate connector, and transmits it to the user through the connector. Users are allowed to provide custom engines by implementing the engine interface, but typically do not need to do so.

(5) Host

Host represents a virtual host, and an engine can contain more than one host. Users typically do not need to create a custom host because the implementation of the host interface given by Tomcat (class Standardhost) provides important additional functionality.

(6) Context

A context represents a Web application that runs on a specific virtual host. What is a Web application? In the Java servlet specification released by Sun, the Web application is defined as follows: "A Web application is a complete application that runs on a Web server, consisting of a set of Servlets, HTML pages, classes, and other resources." It can run in a Web container that implements the Servlet specification in multiple vendors. " A host can contain multiple context (representing a Web application), and each context has a unique path. Users typically do not need to create a custom context, because the implementation of the context interface (class Standardcontext) given by Tomcat provides important additional functionality.

Specific information about each part of the server.xml will be discussed in a separate article. The Tomcat components are shown in Workflow 7.


Figure 7 Working flow diagram for each of the Tomcat components

Tomcat's management program

Tomcat provides a hypervisor: Manager for managing Web applications deployed to the Tomcat server. The manager Web application is included in the Tomcat installation package. To access the Manager Web application, you need to add an account with administrator privileges, edit the%catalina_home%\conf\tomcat-users.xml file, and add the manager role to the <tomcat-users> element , and the user name and password that belong to the role, as shown below.

[HTML]View Plaincopy print?
  1. <? xml version= '1.0 ' encoding=' utf-8 '?>
  2. <tomcat-users>
  3. <role rolename="Manager-gui"/>
  4. <user username="Tomcat" password="Tomcat" roles="Manager-gui"/>
  5. </tomcat-users>

Note: User name and password can be set by themselves, but the role name can only be Manager-gui, not some information mentioned by the manager.

Start the Tomcat server, open the browser, enter in the Address bar: http://localhost:8080/, the page shown in 14 will appear. Click the Manager App link to access the Manager Web app and see the login screen shown in 8.


Figure 8 Tomcat Administrator Login screen

Enter the username tomcat, password 1234, click the "OK" button and you will see the page shown in 9.


Figure 9 Manager Web Application home page

On this page, you can deploy, start, stop, Reload, and uninstall Web applications.

servlet, servlet container, and other content explained

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.