Tomcat loads servlet files-How far can we go series (9)

Source: Internet
Author: User
How far can we go series (9)

Nonsense:

I 've been watching xuanjicao, a record of charm, In the last night to learn about history and culture. It's much better than other programs. I suggest you enjoy it.

There are two stories about reading last week:

First:

There was a chicken farm where thousands of chickens were arranged separately in a small chicken cage. There was a conveyor belt in front of the chicken cage to send food for the chicken, followed by a conveyor belt to send down the eggs. However, I noticed that dozens of chicks were "happy" outside, and the breeders were feeding them.

So I asked: Do you want to help me get these chickens into the cage?

The breeder replied: Oh, these chickens are raised outside. If the chickens in the cage cannot see the free life of some chickens, they will lose confidence and will not get down. Without these chickens, others will give up everything and die.

Suddenly surprised to find out how similar our way of life is to these chickens. How many people are living in cages, watching others explore in the outside world, and realizing their dreams, let's live freely, and then continue the provincial capital in its cage.

The author described that he gave up a year at first, went to the outside world to see it, and finally gave up his career and became the one who was happy and comfortable.

Let me tell you the second story at the end of this article, haha.


Subject:

In the previous topic, we have learned about the servlet workflow: servlet-How far can we go series (7)

Question 1: When will Tomcat load Servlet?

There are two cases
One is load at startup.

One is to load

FirstYesIn web. XML, the <servlet> node is added as follows:<Load-on-startup> 1 </load-on-startup>Node

Example:

   <  Servlet  >      <  Servlet-name  > Dicdatainiter </  Servlet-name  >     <  Servlet-class  > Com. init. dicdatainiter </  Servlet-class  >      <  Load-on-startup  > 2 </  Load-on-startup  >    </  Servlet  >    < Servlet-Mapping  >      <  Servlet-name  > Dicdatainiter </  Servlet-name  >      <  URL-Pattern  > /Dicdatainiter </  URL-Pattern  >    </  Servlet-Mapping > 

 

AboutLoad-on-startup, You need to know:

 
1) Load-on-The startup element indicates whether the container loads the servlet at startup (instantiate and call its Init () method ).2The value must be an integer, indicating the order in which the servlet should be loaded.2) When the value is 0 or greater than 0, it indicates that the servlet is loaded and initialized when the application is started;3If the value is smaller than 0 or is not specified, the container is loaded only when the servlet is selected.4) The smaller the positive value, the higher the servlet priority, the more loaded the application will start.5) When the values are the same, the container selects the order for loading. So,<Load-on-startup> x </load-on-startup>. values 1, 2, 4, and 5 of X indicate priority.

SecondThe process is similar:

Question 2: How does Tomcat loadServletClass?

Based on the previous article on a simple Webserver simulation (how Tomcat works learning-How far can we go series (8), at the end of "loading Servlet classes, we have completed the work before instantiating a servlet instance. We have obtained the URI from the HTTP message and the name of the servlet to be called.

According to how Tomcat works, first create your own servlet: no logic, just generate a class file and put it in the specified folder for loading.

 Package  Code. tomcat. servletcontainer;  Import  Java. Io. ioexception;  Import  Java. Io. printwriter;  Import Javax. servlet .* ;  Public  Class Primitiveservlet Implements  Servlet {  Public   Void Init (servletconfig config) Throws  Servletexception {system. Out. Print ( "Init" );}  Public  Servletconfig getservletconfig (){  Return   Null  ;}  // Once the service method is implemented, the service method of the parent class will not be called to call doget or dopost.      Public   Void  Service (servletrequest req, servletresponse res)  Throws  Servletexception, ioexception {system. Out. Print ( "Service" ); Printwriter writer = Res. getwriter (); writer. println ( "Hello. Roses are red ." );}  Public  String getservletinfo (){  Return  Null  ;}  Public   Void  Destroy () {system. Out. Print ( "Destroy" );}} 

The loading method is as follows:

 Package  Code. tomcat. servletcontainer;  Import  Java. Io. file;  Import  Java. Io. ioexception;  Import  Java.net. malformedurlexception; Import  Java.net. url;  Import  Java.net. urlclassloader;  Import  Java.net. urlstreamhandler;  Import  Javax. servlet. servlet;  Import  Javax. servlet. servletrequest;  Import  Javax. servlet. servletresponse;  Public   Class  Servletprocessor1 { Public   Void  Process (request, response ){  //  Retrieve the URI processed by the request String uri = Request. geturi ();  //  Servlet Class Name String servletname = URI. substring (URI. indexof ("/") + 1 );  //  The Class Loader uses the provided URL directory to load class files. In most casesProgramA Class Loader started in JVM loads the class files we need.  // However, the servlet container, the server that needs to be deployed in a timely manner, must be loaded into the server's project. Urlclassloader loader = Null  ;  //  The urlclassloader constructor requires a URL array, where a class needs to be loaded. URL [] URLs = New URL [1 ];  //  It is used to construct a URL. Although it is null, the compiler does not agree if null is directly used in the URL. Urlstreamhandler streamhandler = Null  ; File classpath =New File ("/webroot" );  Try  {  //  Servlet folder location String repository = ( New URL ("file ", Null , Classpath. GetCanonicalPath () + File. separator). tostring (); URLs [ 0] = New URL ( Null  , Repository, streamhandler ); //  Get the legendary Class Loader Loader = New  Urlclassloader (URLs );}  Catch  (Malformedurlexception e) {e. printstacktrace ();}  Catch  (Ioexception e) {e. printstacktrace ();}  //  After the. Class file is loaded, it is a class instance in Java. Class myclass = Null  ; Try  {  //  Servlet class instance Myclass = Loader. loadclass (servletname );}  Catch  (Classnotfoundexception e) {e. printstacktrace ();} servlet Servlet = Null  ;  Try  {  //  Obtain a servlet instance using the newinstance Method Servlet = (Servlet) myclass. newinstance ();  //  Call the service method of primitiveservlet  Servlet. Service (servletrequest) request, (servletresponse) response );}  Catch  (Exception e) {system. Out. println (E. tostring ());}}} 

In this way, the initial loading step in the servlet process can be barely completed. The implementation in Tomcat is much more complicated. The principle is almost the same, and the foundation is laid first.

About class loading:

In fact, a lot of class loading work needs to be done when Tomcat is started, so Tomcat itself is a Java project.

------------

System. getproperty:

There is a method similar to writing logs:

     /** * Write logs *  @ Param  Logstring *  @ Throws  Ioexception  */      Public   Void Writelog (string logstring) Throws  Ioexception {file logfile = New File ("d :\\ my document \ test. log" );  //  Write Filewriter writer =New Filewriter (logfile, True  );  //  Returns the carriage return sign. String nextline = system. getproperty ("line. separator" ); Writer. Write (logstring + Nextline); writer. Flush (); writer. Close ();} 

System. getproperty ("line. separator")Method.

We can obtain some system-level constants in this way.

Java. version Java Runtime Environment version Java. java. vendor. URL Java vendor's urljava. home Java installation directory Java. VM. specification. version Java Virtual Machine Specification Version Java. VM. specification. java. VM. specification. name Java virtual machine specification name Java. VM. version Java Virtual Machine implementation version Java. VM. java. VM. name Java Virtual Machine implementation name Java. specification. version Java Runtime Environment Specification Version Java. specification. vendor Java Runtime Environment specification vendor Java. specification. name Java Runtime Environment specification name Java.  Class  . Version Java class format version number Java.  Class  . Path Java class path Java. library. the path list searched when the path is loaded. java. io. the default temporary file path of tmpdir is Java. name of the JIT compiler to be used by compiler Java. ext. path of one or more extended directories in dirs OS. name OS. arch operating system architecture OS. version: The version file of the operating system. the separator of the separator file (which is" /") Path. Separator path separator (": "in UNIX systems) line. Separator line separator (in UNIX systems is" / N ") user. Name User's account name user. Home user's home directory user. dir user's current working directory 

Let's talk about the second story:

An Indian and his friends walked to the bustling streets of the United States. The noise of the whole street was almost lost.

Suddenly an Indian said: I heard a cricket scream.

His friend said: What? Are you crazy? In such a quarrel, how can you hear the cry of a cricket?

But the Indian was very certain. He walked across the street to a cement slate, covered with shrubs. He looked in the bush and found a cricket there.

His friend asked: how did you do it?

The Indians said: there is nothing incredible. It depends on what is really important to you. Come here to tell you what's going on.

He took out a coin and threw it to the sidewalk. They found that almost all the people on the sidewalk looked down to see if they left the coin.

Do you understand?It all depends on what is most important to you.

 

Let's move on

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.
Sharing

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.