I saw an article "Beginner Java Web development, please stay away from various frameworks and develop from servlet" in open-source China. I feel ashamed to think that I have been obsessed with various frameworks before. So I read Sun Xin's servlet/jsp in-depth explanation: tomcat-based web development and Lin Xinliang's JSP & servlet learning notes (version 2) and some other related information on the Internet.
Web technology
With the development of Internet technology, web applications based on HTTP and HTML are growing rapidly. Early Web applications were mainly used to browse static pages such as news. Users requested static pages on the server through the HTTP protocol. After the web server software on the server receives the request, they read the resources marked by the URI, in addition, the message is sent to the client browser, which parses HTML and displays the result.
However, with the development of time, users are no longer satisfied with browsing only static pages. Users need some interactive operations to obtain some dynamic results. If HTTP-based software enhancement is too complicated, some extension mechanisms are required to implement the desired functions. The extended web server is CGI (Common Gateway Interface, public gateway interface ). In this way, the user clicks a link or enters a URL to access the CGI program. After receiving the request, the web server runs the CGI program to process the user request, then, the processing result is returned and a response is returned to the Web server. The web server packs the response and returns it to the browser in the form of an HTTP response.
CGI programs solve user needs to some extent. However, there are still some shortcomings, such as the difficulty in writing CGI programs, long response time, and running in process mode leads to limited performance. So in 1997, Sun introduced Servlet technology as a CGI solution for the Java camp.
Servlet and Servlet Container
Java Servlet (Java Server applet) is a Java-based Web component that runs on the server. It is managed by the servlet container and is used to generate dynamic content. Servlet is a platform-independent Java class. compiling a servlet is actually writing a Java class according to the servlet specification. The servlet is compiled as a platform-independent bytecode and can be dynamically loaded to a Web server supporting Java Technology for running.
A servlet container is also called a servlet engine. It is a part of a Web server or application server. It is used to provide network services based on sent requests and responses and decode MIME-based requests, format the mime-based response. The servlet does not have the main method and cannot run independently. It must be deployed in the servlet container to instantiate and call servlet methods (such as doget () and dopost ()), servlet containers include and manage servlets in the servlet lifecycle. After the release of JSP technology, containers that manage and run Servlet/JSP are also called Web containers.
(Note: Common MIME types: text/html, application/pdf, video/QuickTime, application/Java, image/JPEG, application/jar, application/octet-stream, application/X-zip)
With the servlet, you can click a link or directly enter a URL in the address bar of the browser to access the servlet. After the Web server receives the request, it does not directly send the request to the servlet, instead, it is handed over to the servlet container. The servlet container instantiates the servlet and calls a specific servlet method to process the request and generate a response. The response is returned by the servlet container to the Web server. The web server packs the response and sends it to the Web browser in the form of an HTTP response.
What can servlet containers provide?
We know that servlet containers need to be used to manage and run servlets. But why? The reasons for using servlet containers are as follows:
Communication support: using the methods provided by the container, you can easily make the servlet interact with the Web server, instead of creating a serversocket, listening to a port, and creating a stream. The container knows the protocol between itself and the web server, so your servlet does not have to worry about the API between the Web server (such as APACHE) and your web code, you only need to consider how to implement the business logic (such as processing an order) in the servlet ).
Lifecycle management: servlet containers control the birth and death of servlets. servlet containers are responsible for loading classes, instantiating and initializing Servlets, calling servlet methods, and garbage collection of servlet instances. With servlet containers, you do not 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 user requests, if the servlet has run the corresponding HTTP service method, this thread will end. This does not mean that you do not need to consider thread security. In fact, you will encounter synchronization problems, but this will save you a lot of work.
Security of declarations: Using servlet containers, you can use XML deployment description files to configure and modify security without writing hard encoding into servlet-class code.
JSP support: servlet containers translate JSP code into real Java code.
Compared with CGI programs, Servlet has the following advantages:
Servlet is a multi-thread running mode for a single instance. Each request runs in an independent thread, while only one servlet instance provides services.
Servlet is updatable and can respond to more requests, because the servlet container uses a thread rather than an operating system process, and the thread only occupies limited system resources.
Servlet uses standard APIs and is supported by more web servers.
Servlet is written in Java, so it has all the advantages of Java programming language, including ease of Development and platform independence.
Servlet can access the rich class libraries on the Java platform, making development of various applications easier.
The servlet container provides additional functions for the servlet, such as error handling and security.
Servlet container classification
Based on the servlet container working mode, servlet containers can be divided into the following three types:
1) Independent Servlet Container
When we use a Java-based Web server, servlet containers exist as part of the Web server. However, most Web servers are not based on Java. Therefore, the following two servlet container working modes are available.
2) servlet container in process
Servlet containers are implemented by web server plug-ins and Java containers. The Web server plug-in opens a JVM (Java Virtual Machine) in the address space of a Web server so that the Java container can load and run the servlet in this JVM. If a client calls a Servlet Request, the plug-in obtains control of the request and passes it (using JNI technology) to the Java container. Then, the Java container submits the request to the servlet for processing. Servlet containers in processes are very suitable for single-process and multi-thread servers and provide high running speed, but the scalability is insufficient.
3) servlet containers outside the process
The servlet container runs outside the address space of the Web server. It is also implemented by the Web server plug-in and Java container. Web Server plug-ins and Java containers (running in external JVM) use the IPC Mechanism (usually TCP/IP) for communication. When a servlet call request arrives, the plug-in gets control of the request and passes it (using the IPC Mechanism) to the Java container. The response speed of the out-of-process servlet container to customer requests is not as fast as that of the In-process servlet container, but the out-of-process container has better scalability and stability.
Tomcat
To learn Servlet technology, you need a servlet runtime environment, that is, a servlet container. Tomcat is used in this article.
Tomcat is a free open-source servlet container. It is a top-level project of the Apache Software Foundation, developed by Apache, sun, and other companies and individuals. With Sun's participation and support, the latest Servlet and JSP specifications can always be reflected in Tomcat. Tomcat 6 supports the latest servlet 2.5 and JSP 2.1 specifications. Because of its advanced Tomcat technology, stable performance, and free of charge, Tomcat is favored by Java enthusiasts and recognized by some software developers as a popular Web server.
Like web servers such as IIS and Apache, Tomcat can process HTML pages. In addition, it is a Servlet and JSP Container. The independent servlet container is the default Tomcat mode. However, Tomcat is inferior to Apache in processing static html. we can integrate Apache and tomcat for use. Apache serves as an HTTP web server and tomcat serves as a Web container.
The process for the Tomcat server to accept and respond to customer requests is as follows:
1) the client (usually a browser) accesses the Web server and sends an HTTP request.
2) After the Web server receives the request, it passes it to the servlet container.
3) The servlet container loads the servlet, generates the servlet instance, and transmits the objects that represent the request and response to it.
4) The servlet instance uses the request object to obtain the client request information and then process it accordingly.
5) The servlet instance sends the processing result back to the client through the response object. The Container ensures that the response is sent correctly and the control is returned to the web server.
Tomcat installation and configuration
Install JDK before installing Tomcat. There are many online tutorials on JDK download and configuration, which can be Baidu or Google. To download tomcat, first visit the Tomcat project URL: http://tomcat.apache.org/and select the Tomcat program to be downloaded.
For Windows operating systems, Tomcat provides executable installer downloads, that is, the "Windows Service installer" link. To install Tomcat through the installer, Tomcat will be installed as a Windows service.However, we recommend that you download the zip package and decompress it to install Tomcat, because the decompression method is also applicable to other operating systems (such as Linux) and easier to integrate with other development environments. For beginners, you can also better learn the Startup Process of Tomcat.
After downloading the package, decompress the package to the specified directory using WinZip or WinRAR. Then add the bin folder directory under the Tomcat folder in the PATH environment variable, such as D: \ apache-Tomcat-version \ bin. This document uses the latest Apache-Tomcat-7.0.33 version as of the time of writing.
Tomcat directory structure
The directory hierarchy 1 after tomcat installation is shown in.
Figure 1 usage of Tomcat 7.0.33 directory hierarchies is shown in table 1.
Contents |
Chinamoocs |
/Bin |
Stores script files for starting and disabling Tomcat |
/Conf |
Stores various configuration files for the Tomcat server, including server. XML (main configuration file for Tomcat), tomcat-users.xml, Web. xml and other configuration files |
/Lib |
Stores the jar files that Tomcat servers and all web applications need to access. |
/Logs |
Store Tomcat log files |
/Temp |
Store temporary files generated during Tomcat running |
/Webapps |
When a web application is published, the directory and file of the Web application are usually put under this directory. |
/Work |
Tomcat stores the Servlet Source file and bytecode file generated by JSP in this directory. |
Table 1 Tomcat directory structure and usage
As shown in table 1, the jar files stored in the lib directory can be accessed by all web applications. If multiple Web applications need to access the same jar files, you can put these jar files in the lib directory of Tomcat. In addition, for the Java Web application to be introduced later, in its WEB-INF directory, you can also create a lib subdirectory, In the Lib subdirectory can store a variety of jar files, these jar files can only be accessed by the current web application.
Run Tomcat
In the bin sub-directory under the tomcat installation directory, there are some batch files. BAT as the suffix file), where startup. bat is the script file for starting tomcat. Double-click the file with the mouse. If JDK and tomcat have been configured before (the configuration is shown in the PATH variable and java_home variable in figure 2 ), the window shown in 3 is displayed.
Figure 2 JDK and tomcat configuration
Figure 3 Tomcat startup window
Note: If the startup window shown in 3 is not displayed, but the window is flashing, it indicates that JDK and tomcat are not configured properly and can be reconfigured.
Open your browser and enter http: // localhost: 8080/in the address bar (localhost indicates the local machine, and 8080 indicates the default listening port number of Tomcat). The Tomcat page shown in 4 is displayed. To disable the Tomcat server, double-click the shutdown. BAT file in the Tomcat bin directory.
Figure 4 Tomcat default homepage
Tomcat startup Analysis
We use a text editor to open the batch file startup. bat used to start Tomcat and analyze it. The specific analysis process is shown in Figure 5.
Figure 5 Analysis of the startup. BAT file
From the analysis in figure 5, we can see that the startup. Bat script is mainly used to view the directory where the current command is located. Check whether it is in the Tomcat \ or Tomcat \ bin \ directory. View and pass the parameters that call this command to Catalina. bat. Finally, call the Catalina. bat start command. The main function of startup. bat is to call the Catalina. bat start command. Therefore, if you want to use startup to start Tomcat in other directories, you need to set the catalina_home environment variable. Set the value of the catalina_home environment variable to the tomcat installation directory.
Some may wonder why java_home represents the Java installation directory, while tomcat installation directory is not represented by atat_home, but catalina_home. In fact, before Tomcat 4, Tomcat _ home was used to represent the tomcat installation directory.
After resolving the startup. BAT file, let's take a look at the Catalina. BAT file that is actually responsible for starting the Tomcat server. The Catalina. BAT file is relatively long, so the specific analysis process is shown in Figure 6.
Figure 6 Catalina. BAT file Analysis
According to the analysis, Catalina. bat is actually calling Java commands to run the bootstrap class. From the code above, we can see that Tomcat is indeed a pure Java program, and all scripts are finally directly executed using Java commands, which is no different from the Java program we write. However, because there are too many Tomcat modes and various parameters (such as debug and start) are required, you need to use scripts for execution. In addition, by analyzing the Catalina. BAT file, we find that it also calls a file setclasspath. bat. In the setclasspath.batfile, check that the java_homeenvironment variable exists, and use the java_homeenvironment variable to find java.exe to start Tomcat. In this file, other variables are set to call java standard commands. If you are interested, you can analyze the file yourself.
Tomcat Architecture
The Tomcat server is composed of a series of configurable components. The core component is the Catalina servlet container, which is the top-level container of all other Tomcat components. We can view the server. xml file in the conf folder under the tomcat installation folder to understand the hierarchical relationship between Tomcat components. Server. XML has many annotations, which are simplified as follows:
<?xml version='1.0' encoding='utf-8'?><Server port="8005" shutdown="SHUTDOWN"><Service name="Catalina"><Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/><Engine name="Catalina" defaultHost="localhost"><Host name="localhost"><Context path="" docBase="WORKDIR" reloadable="true"/></Host></Engine></Service></Server>
Workdir indicates the path of the project to be imported. The following describes the functions of each component on the Tomcat server.
(1) Server
Server indicates 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. A server container can contain one or more service components.
(2) Service
A service is an intermediate component that lives inside the server. It binds one or more connector components to a separate engine. Server can contain one or more service components. Services are rarely customized by users. Tomcat provides the default implementation of service interfaces, which is simple and can meet the needs of applications.
(3) connector
The connector processes communication with the client. It is responsible for receiving customer requests and returning response results to the customer. You can use multiple connectors in Tomcat.
(4) Engine
In tomcat, each service can only contain one servlet engine ). The engine indicates the request processing pipeline of a specific service. As a service, the engine can have multiple connectors. The engine receives and processes all requests from the connector, returns the response to the appropriate connector, and transmits the response to the user through the connector. Users are allowed to provide custom engines through implementing engine interfaces, but this is usually not required.
(5) Host
Host indicates a virtual host. An engine can contain multiple hosts. Generally, you do not need to create a custom host because the implementation of the host interface (like standardhost) provided by Tomcat provides important additional functions.
(6) Context
A context indicates a web application running on a specific virtual host. What is a Web application? In the java servlet specification released by Sun, a Web application is defined as follows: "A web application consists of a group of servlets, HTML pages, and classes, and other resources constitute a complete application running on the Web server. It can run in Web containers that implement servlet specifications provided by multiple vendors ". A host can contain multiple contexts (representing Web applications), each of which has a unique path. Generally, you do not need to create a custom context, because the implementation of the context interface (like standardcontext) provided by Tomcat provides important additional functions.
The specific information about server. XML is described in another article. The workflow for each Tomcat component is shown in figure 7.
Figure 7 workflow of Tomcat Components
Tomcat Management Program
Tomcat provides a management program: Manager, which is used to manage Web applications deployed on the Tomcat server. The Manager Web application is included in the tomcat installation package. To access the Manager Web application, add an account with administrator privileges, edit the % catalina_home % \ conf \ tomcat-users.xml file, and add the manager role in the <tomcat-users> element, and the username and password of this role, as shown below.
<?xml version='1.0' encoding='utf-8'?><tomcat-users> <role rolename="manager-gui"/> <user username="tomcat" password="tomcat" roles="manager-gui"/></tomcat-users>
Note: the user name and password can be set by yourself, but the role name can only be manager-Gui, not the manager mentioned in some documents.
Start the Tomcat server, open the browser, and enter http: // localhost: 8080/in the address bar. The page shown in figure 14 appears. Click the "Manager app" link to access the Manager Web application. The logon page shown in Figure 8 is displayed.
Figure 8 Tomcat Administrator Logon page
Enter the username Tomcat and password 1234, and click "OK". The page shown in Figure 9 is displayed.
Figure 9 Manager Web application Homepage
On this page, you can deploy, start, stop, reload, and uninstall web applications.
Reprinted please indicate the source: http://blog.csdn.net/iAm333