Servlet principles for Java Learning (Collection)

Source: Internet
Author: User
From: http://blog.csdn.net/dongliheng/archive/2007/06/17/1655052.aspx

This section describes the basic principles of a simple servlet container. There are two servlet containers. The first is very simple, and the second is written according to the first container. In order to make the first container as simple as possible, it is not complete. Some complicated servlet containers (including Tomcat 4 and 5) are described in other chapters on the inside story of Tomcat running.

Both servlet containers process simple Servlet and staticresource. You can use the primitiveservlet In the webroot/directory to test it. Complex servlets will exceed the capacity of these containers. You can learn how to create complex servlet containers from the inside book of Tomcat running.

Two applicationsProgramClasses are encapsulated in the ex02.pyrmont package. You must be familiar with the javax. servlet. servlet interface before understanding how an application works. This interface is introduced first. Next, we will introduce the specific content of the servlet container service servlet.

Javax. servlet. servlet Interface

For servlet programming, the following two classes and interfaces must be referenced: javax. servlet and javax. servlet. http. Among these classes and interfaces, javax. servlet. servlet interfaces are particularly important. All servlets must implement this interface or inherit the classes that have implemented this interface.

The servlet interface has five methods:

<Ccid_nobr>

<Ccid_code> Public void Init (servletconfig config) throws servletexception
Public void Service (servletrequest request, servletresponse response)
Throws servletexception, java. Io. ioexception
Public void destroy ()
Public servletconfig getservletconfig ()
Public java. Lang. String getservletinfo () </ccid_code>

</Ccid_nobr>

The init, service, and destroy methods are servlet lifecycle methods. After the servlet class is instantiated, the container loads init to notify the servlet that it has entered the service column. The init method must be loaded, and the servelt can receive and request. To load the database driver and initialize some values, the programmer can rewrite this method. In other cases, this method is generally null.

The service method is called by the servlet container to allow the servlet to respond to a request. The servlet container passes the javax. servlet. servletrequest object and javax. servlet. servletresponse object. The servletrequest object contains the HTTP request information of the client. The servletresponse encapsulates the servlet response. These two objects, you can write about how the servlet is needed and how the customer requestsCode.

Before deleting a servlet instance from the service, the container calls the destroy method. When the servlet container is closed or the servlet container requires more memory, it is called. This method is called only when all threads in the servlet service method exit, or when it times out. After the servlet container calls the destroy method, it no longer calls the servlet service method. The destroy method gives the servlet the opportunity to clear all the waiting resources (such as memory, file processing, and threads ), to ensure that all the statuses in the memory are synchronized with the Servlet's current status. Listing 2.1 contains the primitiveservlet code. This servlet is very simple. You can use it to test the servlet container application in this article.

The primitiveservlet class implements javax. servlet. servlet and provides interfaces for five servlet methods. The method is also simple: each time the init, service, or destroy method is called, The servlet writes the method name to the control port. The service method also obtains the java. Io. printwriter object from the servletresponsec object and sends the string to the browser.

<Ccid_nobr>

<Ccid_code> listing 2.1.primitiveservlet.java
Import javax. servlet .*;
Import java. Io. ioexception;
Import java. Io. printwriter;
Public class primitiveservlet implements Servlet
{
Public void Init (servletconfig config) throws servletexception
{
System. Out. println (& quot; init & quot ;);
}
Public void Service (servletrequest request, servletresponse response)
Throws servletexception, ioexception
{
System. Out. println (& quot; from service & quot ;);
Printwriter out = response. getwriter ();
Out. println (& quot; Hello. Roses are red. & quot ;);
Out. Print (& quot; Violets are blue. & quot ;);
}
Public void destroy ()
{
System. Out. println (& quot; destroy & quot ;);
}
Public String getservletinfo ()
{
Return NULL;
}

Public servletconfig getservletconfig ()
{
Return NULL;
}
} </Ccid_code>

</Ccid_nobr>

Application 1

Now, let's look at servlet programming from the servlet container perspective. A fully functional servlet container will do the following for each Servlet's HTTP request:

When the servlet is called for the first time, the servlet class is loaded and Its init method is called (only once)

In response to each request, construct a javax. servlet. servletrequest and javax. servlet. servletresponse instance.

Activate the servlet service method and pass the servletrequest and servletresponse objects.

When the servlet class is closed, call the destroy method of the servlet and uninstall the servlet class.

What happens inside the servlet container is much more complicated. This simple servlet container does not have sound functions. Therefore, it can only run very simple servelt and cannot call the init and destroy methods of servlet. However, it also performs the following actions:

Wait for the HTTP request.

Build servletrequest and servletresponse objects

If a staticresource is requested, the process method of the staticresourceprocessor instance is activated and the servletrequest and servletresponse objects are passed.

If the request is a servlet, load the class, activate its service method, and pass the servletrequest and servletresponse objects. Note: In this servlet container, this class is loaded whenever the servlet is requested.

In the first application, the servlet container consists of six classes.

Httpserver1

Request

Response

Staticresourceprocessor

Servletprocessor1

Constants

As shown in the preceding application, the entry (static main method) of this program is the httpserver class. This method creates an httpserver instance and calls its await method. This method waits for the HTTP request, and then creates a request object and a response object, which is assigned to the staticresourceprocessor instance or servletprocessor instance based on whether the request is staticresource or servlet.

The constants class contains static find web_root, which is referenced from other classes. Web_root indicates the primitiveservlet location and the staticresource of Container service.

The httpserver1 instance waits for an HTTP request until it receives a shutdown command. The shutdown command is the same as the previous one.
 

Httpserver1 class

The httpserver1 class in this application is very similar to the httpserver class in the simple Web server application above. However, httpserver1 in this application can serve static resources and servlets. To request a static resource, enter the following URL:

Http: // machinename: Port/staticresource

It is how to request static resources in Web server applications. To request a servlet, enter the following URL:

Http: // machinename: Port/servlet/servletclass

If you want to request a primitiveservle servlet in a local browser, enter the following URL:

Http: // localhost: 8080/servlet/primitiveservlet 

The following listing 2.2 class await method waits for an HTTP request until a shutdown command is released. Similar to the await method mentioned above.

Listing 2.2. httpserver1 class await Method
Public void await (){
Serversocket = NULL;
Int Port = 8080;
Try {
Serversocket = new serversocket (port, 1, inetaddress. getbyname ("127.0.0.1 "));
} Catch (ioexception e ){
E. printstacktrace ();
System. Exit (1 );
}
// Loop, waiting for a request
While (! Shutdown ){
Socket socket = NULL;
Inputstream input = NULL;
Outputstream output = NULL;
Try {
Socket = serversocket. Accept ();
Input = socket. getinputstream ();
Output = socket. getoutputstream ();
// Create a request object and parse it
Request request = new request (input );
Request. parse ();
// Create a response object
Response response = new response (output );
Response. setrequest (request );
// Check whether the request is a servlet or static resource
// The Servlet Request starts with "/servlet /"
If (request. geturi (). startswith ("/servlet /")){
Servletprocessor1 processor = new servletprocessor1 ();
Processor. Process (request, response );
}
Else {
Staticresourceprocessor processor = new staticresourceprocessor ();
Processor. Process (request, response );
}
// Close the socket
Socket. Close ();
// Check whether the previous URI is a shutdown command
Shutdown = request. geturi (). Equals (shutdown_command );
} Catch (exception e ){
E. printstacktrace (); system. Exit (1 );
}
}
}

The difference between the await method in this article and the previous article is that the requests in the await method in this article are scheduled to staticresourceprocessor or ervletprocessor.
If the URI contains "/servlet/.", the request is pushed to the end. Otherwise, the request is passed to the staticresourceprocessor instance.

Request class

The servlet service method accepts the javax. servlet. servletrequest and javax. servlet. servletresponse instances of the servlet container. Therefore, the container must construct the servletrequest and servletresponse objects and then pass them to the service method being served.

The ex02.pyrmont. Request class indicates that a request object is passed to the service method. Similarly, it must implement the javax. servlet. servletrequest interface. This class must provide the implementation of all methods in the interface. Here we try to simplify it and implement only a few methods. To compile the request class, you must provide empty implementations of these methods. Let's take a look at the request class. Internally, all objects that need to be returned to an instance return NULL, as shown below:

Public object getattribute (string attribute ){
Return NULL;
}
Public enumeration getattributenames (){
Return NULL;
}
Public String getrealpath (string path ){
Return NULL;
}

In addition, the request class still needs the parse and geturi methods described above.

Response class

The response class implements javax. servlet. servletresponse. Similarly, this class must provide implementation of all methods in the interface. Similar to the request class, the implementation of other methods except the getwriter method is empty.

Public printwriter getwriter (){
// Autoflush is true, println () will flush,
// But print () will not.
Writer = new printwriter (output, true );
Return writer;
}

The second parameter of the printwriter class builder is whether to enable the autoflush Boolean value. If it is true, flush is output for all calls to the println method. The print call does not flush the output. Therefore, if the print method is called in the last line of the service method of servelt, the output is not visible in the browser. This incompleteness will be adjusted in later applications.

The response class also contains the sendstaticresource method described earlier.

Staticresourceprocessor class

The staticresourceprocessor class is used to serve requests for static resources. The only method is process.

Listing 2.3.staticresourceprocessor class process method.
Public void process (request, response ){
Try {
Response. sendstaticresource ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}

The process method accepts two parameters: request and response instance. It only calls the sendstaticresource method of the response class.

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.