How servlet containers work (3)

Source: Internet
Author: User
Servletprocessor1 class

The servletprocessor1 class is used to process HTTP requests to the servlet. It is very simple and contains only one process method. This method accepts two parameters: A javax. servlet. servletrequest instance and an avax. servlet. servletresponse instance. The process method also constructs a java.net. urlclassloader object and uses it to load servlet class files. On the class object obtained from the class loader, the process method creates a servlet instance and calls its service method.

Process Method

Process Method in listing 2.4. servletprocessor1 class

Public void process (request, response ){
String uri = request. geturi ();
String servletname = URI. substring (URI. lastindexof ("/") + 1); urlclassloader loader = NULL;
Try {
// Create a urlclassloader
Urlstreamhandler streamhandler = NULL;
URL [] URLs = new URL [1];
File classpath = new file (constants. web_root );
String repository = (new URL ("file", null, classpath. GetCanonicalPath () + file. separator). tostring ();
URLs [0] = new URL (null, repository, streamhandler );
Loader = new urlclassloader (URLs );
} Catch (ioexception e ){
System. Out. println (E. tostring ());
} Class myclass = NULL;
Try {
Myclass = loader. loadclass (servletname );
} Catch (exception e ){
System. Out. println (E. tostring ());
} Servlet = NULL;
Try {
Servlet = (servlet) myclass. newinstance ();
Servlet. Service (servletrequest) request, (servletresponse) response );
} Catch (exception e ){
System. Out. println (E. tostring ());
} Catch (throwable e ){
System. Out. println (E. tostring ());
}
}

The process method accepts two parameters: A servletrequest instance and a servletresponse instance. The process method obtains the URI from servletrequest by calling the getrequesturi method.
String uri = request. geturi (); remember the URI format:

/Servlet/servletname

Servletname is the name of the servlet class.

To load the servlet class, use the following code to obtain the servlet name from the URI: String servletname = Uri. substring (URI. lastindexof ("/") + 1); then the process method loads the servlet. To do this, you need to create a class loader and tell the Loader where the class is located. The servlet container can direct the class loader to the directory pointed to by constants. web_root. In the working directory, web_root points to the webroot/directory.

To load a servlet, use the java.net. urlclassloader class, which is an indirect subclass of Java. Lang. classloader. Once you have an instance of the urlclassloader class, you can use the loadclass method to load a servlet class. It is easy to instantiate urlclassloader. This class has three constructors, the simplest of which is:

Public urlclassloader (URL [] URLs );

URLs is a group of objects pointing to its location java.net. url. When a class is loaded, it will automatically search for its location. Any URL Ending with a slash (/) is assumed as a directory. Otherwise, it is assumed as a. jar file, which can be downloaded and opened as needed.

In a servlet container, the position of the class loader to find the servlet class is called the repository ). In the application, the classloader can only search for webroot/directory in the current working directory. Therefore, you must first create a simple set of URLs. The URL class provides multiple constructors, so there are many ways to build a URL object. In this application, the same builder used by another class in Tomcat is used. The builder header (Signature) is as follows:

Public URL (URL context, string spec, urlstreamhandler hander)

Throws malformedurlexception

You can use this builder by passing a specification to the second parameter and passing the null value to the first and third parameters, however, there is another builder that accepts three parameters:

Public URL (string protocol, string host, string file)

Throws malformedurlexception

Therefore, if you only write the following code, the compiler will not know which builder to use:

New URL (null, astring, null );

You can also avoid this problem by telling the compiler the type of the third parameter, for example:

Urlstreamhandler streamhandler = NULL;

New URL (null, astring, streamhandler );

For the second parameter, you can pass the string containing the repository (repository. The following code can be created:

String repository = (new URL ("file", null,

Classpath. GetCanonicalPath () + file. separator). tostring ();

In combination, the following code is part of the process method for building the correct urlclassloader instance.

// Create a urlclassloader
Urlstreamhandler streamhandler = NULL;
URL [] URLs = new URL [1];
File classpath = new file (constants. web_root );
String repository = (new URL ("file", null, classpath. GetCanonicalPath () + file. separator). tostring ()
URLs [0] = new URL (null, repository, streamhandler );
Loader = new urlclassloader (URLs );

The code for creating a repository (repository) is taken from Org. apache. catalina. startup. the createclassloader method in classloaderfactory, and the Code for creating a URL is taken from Org. apache. catalina. loader. the addrepository method in the standardclassloader class. However, you do not need to care about these classes at this stage.

With the class loader, you can use the loadclass method to load the servlet class:

Class myclass = NULL;
Try {
Myclass = loader. loadclass (servletname );
} Catch (classnotfoundexception e ){
System. Out. println (E. tostring ());
}

Then, the process method creates an instance of the mounted servlet class, passes it to javax. servlet. servlet, and activates the servlet service method:

Servlet servlet = NULL;
Try {
Servlet = (servlet) myclass. newinstance ();
Servlet. Service (servletrequest) request, (servletresponse) response );
} Catch (exception e ){
System. Out. println (E. tostring ());
} Catch (throwable e ){
System. Out. println (E. tostring ());
}

Compile and run the application
To compile the application, enter the following command in the working directory:
Javac-D.-classpath./lib/servlet. Jar src/ex02/pyrmont/*. Java
If you want to run the application in windows, type the following command in the working directory:
Java-classpath./lib/servlet. jar;./ex02.pyrmont. httpserver1
In Linux, use colons to separate class libraries:
Java-classpath./lib/servlet. jar:./ex02.pyrmont. httpserver1
To test the application, enter the following command in the URL or browser address bar:
Http: // localhost: 8080/index.html
Or:
Http: // localhost: 8080/servlet/primitiveservlet
You will see the following text in your browser:
Hello. Roses are red. 
Note: you cannot see the second line of characters (Violets are blue), because only the first line of characters are sent to the browser. The subsequent chapter will show you how to solve the problem.

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.