Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!
In the First tomcat attempt, we set up a basic environment for testing Servlet and JSP. Now we need to turn to the specific development of network applications.
Chef
The basic way for Web servers to work isRequest-processing-reply. Requests and replies are communication over the network based on the HTTP protocol (refer to the HTTP protocol ). The request is a customer's order, and the response is like a waiter serving food, while the process is in the kitchen. The cook prepares the food according to the requested menu.
A chef is usually an application on a server.Program. This application can extract the information in the request and prepare a response based on the information. Such applications can be written in many languages, such as C, C ++, Perl, Ruby, Python, Ruby, and PHP. Because of the different design concepts and compiler features of different languages, the applications written in these languages also have different characteristics (various chefs ). For example, the C and C ++ languages have high operating efficiency, a wide range of PHP Web applications, and convenient development of Ruby and python.
(In the language competition, the "Kitchen" of web servers is a battle for troops)
Servlet is a "cook" provided by Java ". In Java, "Everything is an object ". Servlet is a special type of Java object. Java uses servlet objects to process HTTP requests.
Example
The following is a simple servlet example. The source file isTestpage. Java:
Package Foo; Import Javax. servlet .* ; Import Javax. servlet. http .* ; Import Java. Io .* ; Public Class Testpage Extends Httpservlet { Public Void Doget (httpservletrequest request, httpservletresponse response) Throws Ioexception, servletexception {printwriter out = Response. getwriter (); Out. println ( "<HTML> <body>" + "<p> Hello world! </P> "+" </body> );}}
The function of this servlet is to reply to the string"<HTML> <body> <p> Hello world! </P> </body> ". This string is actually an HTML text. It is sent back to the client as the main part of the HTTP response.
A testpage class is defined here, which inherits the httpservlet abstract class (see httpservlet ). We have coveredDoget ()Method. Doget () Method ProcessingGetMethod. If the HTTP request method is post, it should overwriteDopost ()Method. Each servlet should overwrite one of doget () and dopost. The doget () and dopost () methods receive two request and Response parameters:HttpservletrequestTypeAndHttpservletresponseType. The two parameters represent the request and response of the HTTP Communication respectively.
Httpservletrequest and httpservletresponse are two interfaces. Within the method, we can operate the request and response objects. For example, the getwriter method of response is used to obtain the writer and write the HTML text. The written text will be transmitted back to the client as the body of the HTTP response. For example, we can use the getmethod () method of the request to obtain the HTTP request method. Refer to the following official documents:
More methods of httpservletrequest
More methods of httpservletresponse
In addition, the printwriter class comes from the java. Io package. Refer to Java Io
Doget () is a real studio. We define this method (or dopost () to let the cook do specific things. The key to servlet writing is to write a doget () method or dopost () method that meets the requirements.
Doget () and dopost ()
As in the first linePackageAs described in the statement (refer to the Java package), The testpage class is put into the foo package. We alsoImportOther Java packages. Servlet is based on Java, so it can use the rich tools provided by the Java language.
Compile
Use the following command to compile testpage. Java
$ Javac-classpath/Path-to-Tomcat/Lib/servlet-api.jar: classes:. testpage. Java
The above path-to-Tomcat is the installation path of Tomcat. We need to include the servlet-api.jar because the javax. servlet package belongs to J2EE and does not belong to JSE.
Put the compiled testpage. Class file into the following folder. (If the folder does not exist, you need to create it yourself ):
// Path-to-Tomcat/webapps/test/WEB-INF/classes/foo
(In tespage. Java, the package statement indicates that the class is in the foo package. The path here complies with the previous package definition .)
Modify or create/path-to-Tomcat/webapps/test/Web-info/Web. xml
<? XML version = "1.0" encoding = "ISO-8859-1" ?> <! -- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. see the notice file distributed with this work for additional information regarding copyright ownership. the ASF licenses this file to you under the Apache license, version 2.0 (the "License"); you may not use this file license t in compliance with the license. you may obtain a copy of the license athttp: // your unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "as is" basis, without warranties or conditions of any kind, either express or implied. see the license for the specific language governing permissions and limitations under the license. --> < Web-app Xmlns = "Http://java.sun.com/xml/ns/javaee" Xmlns: xsi = "Http://www.w3.org/2001/XMLSchema-instance" Xsi: schemalocation = "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" Version = "3.0" Metadata-complete = "True" > < Servlet > < Servlet-name > Test </ Servlet-name > < Servlet-class > Foo. testpage </ Servlet-class > </ Servlet > < Servlet-Mapping > < Servlet-name > Test </ Servlet-name > < URL-Pattern > /Myservlet </ URL-Pattern > </ Servlet-Mapping > </ Web-app >
Such an XML file is called deployment description (Dd, Deployment descriptor ). Dd tells container how to run Servlet and JSP.
The <servlet> label above refers to the servlet (FOO. testpage. Class)NameIs test.
In the <servlet-mapping> label, test the ServletCorrespondingAt URL:/myservlet. This indicates that when a request accesses the URL, the request is passed to the servlet test for processing.
The main purpose of the above modification is to describe the servlet and URLCorrespondence.
Then, you can access localhost: 8080/test/myservlet to view the access page.
Process
Let's take a look at the Servlet's process of processing a request:
Send an HTTP request from the client (guest) to the server, which is passed to the servlet container. The container is responsible:
- Analyze the HTTP request information and create a newRequest objectPut the information in the HTTP request into the request object.
- NewResponse object
- Search by web. xmlServlet object corresponding to the URL. If the servlet object does not exist, create a new servlet object.
- Create a newThreadTo process this request. A thread can reference requests and response objects.
The thread will call the servlet doget () or dopost () method. After the thread finishes running, the response object will be returned to the container. The container generates an http-compliant response based on the information in the response object and sends it back to the client.
Note that even the newly created servlet object will not end with the end of the thread. The servlet will continue to exist. You do not need to create a servlet for the next access with the same URL.
Summary
A simple servlet was created above, which is mainly used to illustrate the process of servlet production. Many of Servlet's powerful functions will be available soon.
Each servlet is like a chef. We can use different URLs to select different chefs. A complex website often requires many servlets with different functions.
Welcome to continue reading the "Java quick tutorial" SeriesArticle