Servlet-How far can we go series (7)

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

I wish you a happy long vacation, hard work at work, and hard work at rest and enjoyment.

Today, let's get off with you after the holiday. Haha!

 

The core class diagram of servlet is as follows:

The servlet above is just an interface, which is equivalent to describing the servlet standard,That is to say, it has nothing to do with the protocol.. The implementation of httpservlet is based on the HTTP protocol. See the following:

When you open the source code, you can see that most interfaces and abstract classes are used. Where are the actual implementations? In the servlet containerSource codeIs a servlet container like tomcat.

So I think this is understandable.SRole of ervlet: it provides control buttons, once these buttons are installedSIn the ervlet container, we can use these buttons to manipulate the servlet container to manage our ownSErvlet instance.

This is important.So read SErvletThe source code is actually to understand its basic structure and API. What we really want to read is the source code of Tomcat!

 

ServletRunning structure and API:

First, let's take a look at the next HTTP request-response process:
AFirst, the client sends an HTTP request to the server through a browser;
BTomcat listens to port 8080 of the server. After an HTTP request is sent, the project name is parsed and the project folder is found in the webapps directory.
CTomcat is used as the servlet container to instantiate the servlet instance called by the first request (the first instance will be used for the same Servlet request later ).
D, Call the init () method to initialize the job.
ETo call the service method of httpservlet. More requests will be made in the middle. Call the doget or dopost method to execute the core logic.Code.
FAfter the servlet is executed, the response is returned, and the client browser displays the effect based on the response.

Then let's look at the basic operating mechanism:

As shown in the figure,Different user requests use the same servlet instance concurrentlyThis is an important basic mechanism.

After the container parses the HTTP request, the servlet is instantiated. Because it is an HTTP request, the HTTP servlet code is executed:

First,Service (servletrequest req, servletresponse res)Method:

    Public   Void  Service (servletrequest req, servletresponse res)  Throws  Servletexception, ioexception {httpservletrequest request; httpservletresponse response;  Try  {Request = (Httpservletrequest) req; //  Convert requests to HTTP requests Response = (httpservletresponse) RES; //  Convert response to HTTP Response } Catch (Classcastexception e ){  Throw   New Servletexception ("non-http request or response" );} Service (request, response );  //  Call the HTTP service method }

Then the Service (httpservletrequest req, httpservletresponse resp) method will be called:

 Protected   Void  Service (httpservletrequest req, httpservletresponse resp)  Throws  Servletexception, ioexception {string method = Req. getmethod (); //  Obtain the method type in req          If (Method. Equals (method_get )){ //  Depending on the method type, we only focus on doget and dopost.              Long Lastmodified = Getlastmodified (req );  If (Lastmodified =-1 ) {Doget (req, resp );}  Else  {  Long Ifmodifiedsince =Req. getdateheader (header_ifmodsince );  If (Ifmodifiedsince <(lastmodified/1000*1000 ) {Maybesetlastmodified (resp, lastmodified); doget (req, resp );  //  In this way, we can execute the doget method written by ourselves to execute our own business logic. } Else  {Resp. setstatus (httpservletresponse. SC _not_modified );}}}  Else   If  (Method. Equals (method_head )){ Long Lastmodified = Getlastmodified (req); maybesetlastmodified (resp, lastmodified); dohead (req, resp );}  Else   If  (Method. Equals (method_post) {dopost (req, resp );}  Else   If  (Method. Equals (method_put) {doput (req, resp );}  Else   If  (Method. Equals (method_delete) {dodelete (req, resp );} Else   If  (Method. Equals (method_options) {dooptions (req, resp );}  Else   If  (Method. Equals (method_trace) {dotrace (req, resp );}  Else { //  Does not belong to the HTTP method type. Error 501 is returned. String errmsg = lstrings. getstring ("HTTP. method_not_implemented" ); Object [] errargs = New Object [1]; Errargs [ 0] = Method; errmsg = Messageformat. Format (errmsg, errargs); resp. senderror (httpservletresponse. SC _not_implemented, errmsg );}} 

The servlet we implement by ourselves, we only need to inheritHttpservlet, ImplementationDogetOK:

  Public   class  helloworld  extends   httpservlet {  private   static   final   long  serialversionuid = 1l ;@ override   protected   void   doget (httpservletrequest req, httpservletresponse resp)   throws   servletexception, ioexception {system. out. println ( "test" ); getservletcontext (). getrequestdispatcher ( "/JSP/test.html"  ). forward (req, resp) ;}< br>  

To pay attention to the following when running servlet:
A. servlet lifecycle:
Servlet class loading ---> instantiation ---> service ---> destruction

B. Three Methods represent the servlet lifecycle:
1. init method: initializes the servlet object.
2. service method: responds to customer requests.
3. Destroy method: When the servlet Object exits the lifecycle, it is responsible for releasing the occupied resources.

C. Execute yourselfServletImportant parameters:

1. httpsession: one connection to the client is closed,It is managed at the client connection level.
2. servletconfig: After being instantiated from a servlet, it is valid for any client access at any time, but only for this servlet
Valid. The servletconfig object of one servlet cannot be accessed by another servlet.From a singleServletManagement.
3. servletcontext: valid for any servlet and anyone at any time. This is a truly global object.From allServletManagement

4,Httpservletrequest, httpservletresponse:From a singleServletTo manage a single response side.

D. API

Httpservletrequest:

View code

String getauthtype () if the servlet is protected by an authentication scheme, for example, HTTP basic authentication, the scheme name is returned. String getcontextpath () returns the prefix of the URL of the specified servlet context (Web application. Cookie [] getcookies () returns an array of request-related cookies. Long getdateheader (string name) converts the output to a simplified version of getheader () suitable for building the long value of the date object. String getheader (string name) returns the specified HTTP header identifier. If the name is provided by the request, the name is case-insensitive. Enumeration getheadernames () returns the weights of all HTTP header names given in the request. Enumeration getheaders (string name) returns the enumerated values of all HTTP header names of the specified type in the request. It is very useful for header labels with multiple values.  Int  Getintheader (string name) converts the output to a simplified version of getheader () of the int value. String getmethod () returns the HTTP request method (such as get and post) string getpathinfo () returns any additional path information specified in the URL. String getpathtranslated () returns any additional path information specified in the URL. the quilt is converted into an actual path. String getquerystring () returns the query string, that is, in the URL ?The following section. String getremoteuser () if the user passes the authentication, the remote user name is returned; otherwise, the value is null. String getrequestedsessionid () returns the client's session ID string getrequesturi () returns a part of the URL from / ", Including the context, but not any query string. String getservletpath () returns the child string httpsession getsession () after the request URI context to call getsession (  True  . Httpsession getsession (  Boolean  Create) returns the current HTTP session. If it does not exist, a new session is created. The create parameter is true. Principal getprincipal () if the user passes the authentication, the Java. Security. principal object representing the current user is returned; otherwise, the value is null.  Boolean  Isrequestedsessionidfromcookie () If the requested session ID is provided by a cookie object, true is returned; otherwise, false is returned. Boolean  Isrequestedsessionidfromurl () If the requested session ID is decoded in the request URL, true is returned; otherwise, false is returned.  Boolean  Isrequestedsessionidvalid () returns true if the session ID returned by the client is still valid. Boolean isuserinrole (string role) returns true if the user has been authenticated to be related to the specified role. If the user is not authenticated or fails to pass the authentication, false is returned. 

Httpservletresponse:

View code

 Void Addcookie- The cookie header is added to the response.  Void Adddateheader (string name, Long Date) use the specified date value to add a response header with the specified name (or replace all the response headers.  Void  Setheader (string name, string value) sets a response header with the specified name and value.  Void Addintheader (string name, Int  Value) use the specified integer value to add the response header with the specified name (or replace all header labels with this name ).  Boolean  Containsheader (string name) returns true if the response contains the header mark of this name. String encoderedirecturl (string URL) if the client does not know to accept cookid, the session ID is added to the URL. The first method only calls the URLs used in sendredirect. Other encoded URLs should be passed to encodeurl () string encodeurl (string URL)  Void Senderror (Int  Status) sets the response status code to a specified value (optional status information ). Httpservleetresponse defines a complete set of Integer constants to indicate valid State values.  Void Senderror ( Int  Status, string MSG)  Void Setstatus ( Int Status) specifies the response status code. Only applicable to the response that does not generate an error, while the error response uses senderror ().

ServletContext:

 

View code

Object getattribute (string name) returns the object with the specified name in the servlet context, or binds an object with the specified name. From the standard perspective of Web applications, such objects are global objects because they can be accessed by the same servlet at another time. Or any other servlet access in the context.  Void  Setattribute (string name, object OBJ) sets the object with the specified name in the servlet context. Enumeration getattributenames () returns an enumeration of all attribute names stored in the servlet context. Servletcontext getcontext (string uripath) returns the servlet context mapped to another URL. In the same server, the URL must be / . String getinitparameter (string name) returns the initialization parameter value of the specified context range. This method is different from the name of the servletconfig method. The latter is only applicable to the encoded specified servlet. This method is applied to all parameters in the context. Enumeration getinitparameternames () returns (may be blank) the enumerated value of the name of the initialization parameter value for the specified context range.  Int  Getmajorversion () returns the maximum and minimum versions supported by Servlet APIs in this context. Int  Getminorversion () string getmimetype (string filename) returns the MIME type of the specified file name. Typically, it is based on the file extension rather than the content of the file itself (it does not have to exist ). If the MIME type is unknown, null is returned. Requestdispatcher getnamedispatcher (string name) returns the requestdispatcher of the servlet or JSP with the specified name or path. If requestdispatch cannot be created, null is returned. If the path is specified, / "And is relative to the top of the servlet context. Requestdispatcher getnamedispatcher (string path) string getrealpath (string path) specifies a URI and returns the absolute path of the URI in the file system. If the ing is not allowed, null is returned. URL getresource (string path) returns the URL corresponding to the specified absolute path of the servlet context or the input stream that reads the URL. If the resource does not exist, null is returned. Inputstream getresourceasstream (string path) string getserverinfo () returns the name and version number of the servlet engine.  Void  Log (string message) Void  Log (string message, throwable t) writes a message to the servlet registration. If the throwable parameter is provided, the stack track is included.  Void Removeattribute (string name) deletes the specified attribute from the servlet context.

 

Httpsession:

 

View code

 Object getattribute (string name) saves an object in a session as the specified name, and returns or deletes the previously saved name object.  Void  Setattribute (string name, object value)  Void Removeattribute (string name) Enumeration getattributename () returns the enumerated values of all attribute names bound to the current session.  Long  Getcreationtime () returns a long integer that represents the session creation and last access date and time. This integer is used in the Java. util. Date () constructor.  Long  Getlastaccessedtime () string GETID () returns the session ID, a unique keyword set by the servlet engine. If ing getmaxinactiveinterval () does not interact with the client, set and return the maximum number of seconds for session survival.  Void Setmasinactiveinterval ( Int  Seconds)  Void  Invalidate () causes the session to be terminated and any objects in the session are released. Boolean Isnew () returns true if the client is not added to the session. When a session is created for the first time and the session ID is passed into the client, but the client does not perform the second request containing the session ID, true is returned.

 

Servletconfig:

View code

Getservletname () method Overview:PublicJava. Lang. String getservletname () This method returns the name of a servlet instance, which is provided by the server administrator. Getservletcontext () method Overview:PublicServletcontext getservletcontext () returns a reference to a servletcontext object. Getinitparameter () method Overview:PublicJava. Lang. String getinitparameter (Java. Lang. string name) returns the value of an initialization variable determined by the string name parameter. If the variable does not exist, null is returned. Getinitparameternames () method Overview:PublicJava. util. Enumeration getinitparameternames () returns an enumeration function that stores all initialization variables. If the servlet does not initialize the variable, an empty enumeration function is returned.

Apart from the above, there is still a lot of content to be learned in actual encoding.

 

Summary:

In the end, we had to read the source code of Tomcat to answer more questions.

 

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

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

Related Article

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.