Servlet Technology Summary

Source: Internet
Author: User
From: http://blog.csdn.net/yinyuan1987/archive/2008/11/29/3410469.aspx

1. servlet Introduction

Java Servlet is a platform-independent server component that can run in servlet containers. the servlet container is responsible for the communication between the servlet and the customer and the method for calling the servlet. The communication between the servlet and the customer adopts the "Request/response" mode.

2. servlet API

The servlet framework consists of two Java packages: javax. servlet and javax. servlet. HTTP. The javax. servlet package defines common interfaces and classes that must be implemented or extended for all Servlet classes. The javax. servlet. http package defines the HTTP servlet class for communication over HTTP.

The core of the servlet framework is the javax. servlet. servlet interface, which must be implemented by all servlets. Five methods are defined in the servlet interface. Three of them represent the servlet lifecycle.

Init method, responsible for initializing servlet objects

Service method, responsible for responding to customer requests

The destroy method is used to release the occupied resources when the servlet Object exits the lifecycle.

When you develop your own servlet class, the servlet class must expand one of the following two classes

(1) extended genericservlet class:

If the servlet extends the genericservlet class, the service method must be implemented because the service method in the genericservlet class is declared as an abstract method. The Declaration Form of this method is as follows:

public abstractvoid service(ServletRequest request,ServletResponse response)throwsServletException,IOException

The service method has two parameters: servletrequest and servletresponse. The servlet container encapsulates the customer's request information in the servletrequest object and sends it to the service method. The service method sends the response result to the customer through servletresponse.

(2) extended httpservlet class:

If the servlet class extends the httpservlet class, you do not need to implement the service method because the httpservlet class has implemented the service method. The Declaration Form of this method is as follows:

protected voidservice(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException

In the service method of httpservlet, first obtain the HTTP Request Method information from the httpservletrequest object, and then call the corresponding method according to the request method.

HTTP requests include Delete, get, options, post, put, and trace. Corresponding methods are provided in the httpservlet class, such as dodelelte (), doget (), dooptions (), dopost (), doput (), and dotrace ()

The service method of httpservlet also has two parameters: httpservletrequest and httpservletresponse. These two classes expand the servletrequest and servletresponse interfaces respectively.

Servletrequest interface: The servletrequest interface encapsulates the customer request information, such as the customer request method, parameter name and parameter value, the protocol in use by the client, and the remote host information that sends the customer request. The servletrequest interface also provides servlet with servletinputstream that reads the customer request data stream in binary mode. The subclass of servletrequest can provide servlet with more data related to specific protocols.

Servletrequest interface: The servletrequest interface provides the servlet with a method to return the response results. It allows the servlet to set the length and Mime Type of the returned data, and provides the output stream servletoutputstream. The servletresponse subclass provides more methods related to specific protocols.

3. servlet Lifecycle

The servlet lifecycle begins when it is loaded into the servlet container and ends when it is terminated or re-loaded. The servlet lifecycle can be divided into three stages: initialization, response to customer requests, and termination. The javax. servlet. servlet interface defines three methods: Init (), service (), and destroy (), which will be called at different stages of the servlet respectively.

(1) initialization phase

The servlet container automatically loads the servlet in the following circumstances:

Some servlets are automatically loaded when the servlet container starts.

After the servlet container is started, the customer sends a request to the servlet for the first time.

After the servlet class file is updated, reload the Servlet

After the servlet is loaded, the servlet container creates a servlet instance and calls the servlet Init () method for initialization. During the entire servlet lifecycle, The init method is called only once. The init method can be overloaded in two ways:

public voidinit(ServletConfig config) throws ServletException;public void init()throws ServletException;

During servlet initialization, the servlet container creates a servletconfig object for the servlet to store the Initialization Configuration Information of the servlet, such as the initial parameters of the servlet. If the servlet class overwrites the first init method with parameters, you should first call super. the init (config) method ensures that the parameter config references the servletconfig object. If the second init method without parameters is overwritten, super. init () method. To access the servletconfig object in the init method, you can call the getservletconfig () method of the servlet class.

(2) response to customer requests

For customer requests that reach the servlet container, the servlet container creates the servletrequest object and servletresponse object specific to this request, and then calls the servlet service method. The service method obtains and processes the customer request information from the servletrequest object, and returns the response result to the customer through the servletresponse object.

(3) termination stage

When the web application is terminated, the servlet container stops running, or the servlet container reloads the Servlet's new instance, the servlet container first calls the Servlet's destroy method. In the destroy method, resources occupied by servlet can be released.

4. HTTP and httpservlet

HTTP is a request/response mode-based protocol. The client sends a request and the server returns the response to the request. HTTP uses a reliable TCP connection. The default port is 80.

In HTTP, sessions between clients and servers are always initialized by the client by establishing a connection and sending an HTTP request. The server does not actively contact the client or require a connection with the client. After the session starts, the browser or server can interrupt the connection at any time. For example, you can click the "stop" button to interrupt the current file download process when you browse the webpage, disable the HTTP connection to the Web server

4.1. http request

An HTTP request consists of three parts:

Request Method URI protocol/version

Request Header

Request body

For example:

GET /sample.jspHTTP/1.1Accept:image/gif.image,image/jpeg.*.*Accept-Lauguage:zh-cnConnection:Keep-AliveHost:localhostUser-Agent:Mozilla/4.0Accept-Encoding:gzip,deflateusername=weiqin&password=1234

(1) Request Method URI protocol/version

GET/sample. jsphttp/1.1

According to HTTP standards, HTTP requests can use multiple request methods. For example, HTTP 1.1 supports seven request methods: Get, post, Head, options, put, delete, and trace.

Uri completely specifies the network resource to be accessed. Generally, you only need to give a relative directory relative to the root directory of the server. Therefore, it always starts "/".

The Protocol version declares the HTTP Version Used during communication.

(2) Request Header

The request header contains many useful information about the client environment and request body.

(3) Request body

The request header is an empty line between the request header and the request body. This line is very important. It indicates that the request header has ended, followed by the request body. The request body can contain the query string information submitted by the customer.

4.2. Http response

Similar to HTTP requests, HTTP responses are composed of three parts:

Protocol Status Code Description

Response Header

Response body

HTTP/1.1 200 okserver: apachetomcat/5.0 Date: Mon, 6 oct2003 13:13:13 gmtcontent-type: text/htmllast-modified: Mon, 6 Oct 2003 13:03:13 gmtcontent-length: 112 <HTML> 

(1) Protocol Status Code Description

The first line of the HTTP response is similar to the first line of the HTTP request. It indicates that the communication protocol is HTTP 1.1, and the server has successfully processed the request sent by the client.

(2) Response Header

The Response Header also contains a lot of useful information like the request header, such as the server type, date and time, content type, and length.

(3) response body

The response body is the HTML page returned by the server. The response header and body must be separated by blank lines.

4.3. Functions of httpservlet

After understanding the specific HTTP protocol specifications, you can better understand the role of httpservlet. It can generate corresponding HTTP Response Results Based on the HTTP request sent by the customer. Httpservlet must first read the content of the HTTP request. The servlet container is responsible for creating the httpservletrequest object and encapsulating the HTTP request information into the httpservletrequest object, which greatly simplifies the workload of HTTP servlet to parse request data. Without httpservletrequest, httpservlet can only directly process the original string data sent by the Web Client. With httpservletrequest, you only need to call the relevant methods of httpservletrequest to conveniently read any part of the HTTP request information.

Common Methods for reading HTTP request information in httpservletrequest:

Getcookies (): Return HTTP request cookies

Getrequesturi (): returned HTTP request URI

Getquerystring (): return the query string in the HTTP request data

Getmethod (): return the HTTP Request Method

The servlet container also provides the httpservletresponse object to httpservlet, which can be used to generate each part of the HTTP response.

Httpservletresponse provides the following methods to generate response data headers:

Addcookie (cooliecookie): adds a cookie to the HTTP Response

Setheader (stringname, string value): sets the HTTP response header.

 

4.4. Steps for the servlet container to respond to a Web client request:

(1): Web customers send HTTP requests to servlet containers;

(2): The servlet container parses the HTTP request of the Web Client;

(3): The servlet container creates an httprequset object, which encapsulates HTTP request information;

(4): The servlet container creates an httpresponse object;

(5): The servlet container calls the service method of httpservlet and transmits the httprequest and httpresponse objects as parameters of the service method to the httpservlet object;

(6): httpservlet calls httprequest methods to obtain HTTP request information.

(7): httpservlet calls httpresponse methods to generate response data

(8): The servlet container sends the HTTP servlet response result to the Web Client.

5. Create an httpservlet

Creating your own httpservlet class usually involves the following four steps:

(1) Extend the HTTP servlet abstract class

(2) Some methods that overwrite httpservlet, such as the doget or dopost Methods

(3) obtain the HTTP request information. For example, you can use the httpservletrequest object to retrieve the data submitted by the HTML form or the query string on the URL. Whether it is HTML form data or a query string on the URL, it is stored in the httpservletrequest object as a parameter name/parameter value.

(4) generate HTTP response results. You can use the httpservletresponse object to generate response results. The httpservletresponse object has a getwriter () method, which returns a printwriter object. The print () or println () method of printerwriter can be used to send string data streams to the client.

6. Relationship between servletcontext and Web applications

The servlet container loads the web application at startup and creates a unique servletcontext object for each web application. Servletcontext can be viewed as the shared memory of the server component of a Web application.

Attributes set in servletcontext always exist during running of the Web application. When the web application is disabled, the servlet container will destroy the servletcontext object, and the attributes stored in the servletcontext object will naturally no longer exist. The servletcontext of different applications is independent.

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.