Web Container and Servlet

Source: Internet
Author: User
Tags standalone web server terminates

Turn from: Http://www.360doc.com/content/10/0713/20/495229_38798294.shtmlWeb Server and Web application layer is not two categories, in order to let them two writing, First, apply the intermediary to develop Web Apps and Web A standard interface for server collaboration, Servlet is one of the main protocols, interfaces

A series of standard Java interfaces that Web applications collaborate with a Web server, collectively known as the Java Servlet API. There are also some servlet specifications. Servlet specification to be able to publish and run the Java Web web of the app container server called Servlet container .

Servlet Container

As specified by the servlet, the corresponding client requests access to the specific servlet process as follows:

1. The client makes the request.

2. The servlet container receives client request resolution.

3. The servlet container creates a ServletRequest object.

It contains customer request information and other information about the customer such as request header, request body, client IP, etc.

4. Container to create a Servletresponse object.

5. The container invokes the service method of the servlet requested by the client and passes ServletRequest and servletresponse as parameters.

6. The servlet obtains customer request information from the customer's parameters.

7. The servlet uses Servletresponse objects to produce the corresponding results.

8. The servlet container sends the results generated by the servlet to the customer.

Tomcat Working mode

① stand-alone servlet container

Tomcat runs separately as a standalone Web server.

② servlet containers in other Web server processes

In this mode, Tomcat is both part of the Web server plug-in and the servlet container component. The Web server plug-in launches a Java virtual machine in the internal address space of another Web server process, and the servlet container component runs in this Java virtual machine. If there is a servlet request, the Web server plug-in obtains this request and forwards it to the servlet container (JNI communication, Java Local call interface).

3 other Web server out-of-process servlet containers

Similar to the above, just at the Web server external address, start a Java Virtual machine process, forward with the IPC communication mechanism, a mechanism for communication between two processes.

Servlet Container

Servlets are the most core components of Java Web applications and are most commonly used:

1. Request Objects ServletRequest and HttpServletResponse

2. Response Object servletresponse, HttpServletResponse

3. Servlet Configuration object, ServletConfig, when the container initializes a servlet, it provides him with a ServletConfig object that the servlet uses to get initialization parameter information and ServletContext object.

4. ServletContext Object: It provides access to the various resources provided by the container for the current Web application

Consisting primarily of two Java packages, Javax.servlet and Javax.servlet.http define the servlet interface and related common interfaces and related classes, which define the HTTP protocol.

Servlet Interface

At the core of the Servlet API, all servlets must implement this interface, defining 5 methods, 3 of which are called by the container, and the container invokes a particular method at different stages of the servlet's life cycle.

1.Init

2.Service (ServletRequest req,servletresponse Res), invoking the Service method when responding to a client request, accessing a specific Servlet object

3.destory (): Responsible for releasing the resource occupied by the Servlet object, which is called by the container when the Servlet object ends its life cycle

4.getServletConfig: Returns a ServletConfig object. All the Servlets

5.getServletInfo: Returns a string that returns the Servlet creator, version, copyright information, and so on.

Genericservlet

Abstract class, implements the Servlet interface, ServletConfig interface, serializable interface. In this way, all Servlets pass through the Serletconfig interface and have the means to obtain their own relevant properties: Getinitparameter,getinitparameternames. In addition, there are getservletcontext, but also the implementation of the Config interface needs to be implemented.

ServletConfig

<servlet>

<servlet-name>....</servlet-name>

<servlet-class>.....</servlet-class>

<init-param>

<param-name>....<param-name>

<param-value>....<param-value>

</init-param>

</servlet>

<servlet-mapping>

</servlet-mapping>

The servlet init (servletconfig config) method has this parameter, which initializes a Servlet object and creates a ServletConfig object that contains the initialization parameter information for the servlet.

ServiceConfig also has an API associated with the current ServletContext object.

After a servlet is instantiated, access to any client at any time is valid, but only for this servlet , and one servlet's ServletConfig object cannot be accessed by another servlet .

Getinitparameter ()/getinitparameter (String name), used to get initialization parameters, Getservletcontext

Getservletname: Returns the name of the servlet that is the value of the corresponding servlet element <servlet-name> element in the Web xml:

HttpServlet Abstract class

Genericservlet subclasses, although custom, servlet classes can be genericservlet, but all extend the HttpServlet class. It is the HTTP request way, respectively implement the corresponding method, Doget, DoPost, DoDelete, from the source view, it implements the Servlet interface service (ServletRequest req,servletresponse Res) method, and overloads the method, service (Httpservicerequest Req,httpservletresponse Rep).Introduction to the HTTP protocol Request method featureprivate static final String Method_delete = "DELETE";
private static final String Method_head = "HEAD";
private static final String Method_get = "GET";
private static final String method_options = "OPTIONS";
private static final String Method_post = "POST";
private static final String Method_put = "PUT";
private static final String Method_trace = "TRACE";

protected void Service (httpservletrequest req, HttpServletResponse resp)

throws Servletexception, IOException

{

String method = Req.getmethod ();

if (Method.equals (method_get)) {

long lastmodified = getlastmodified (req);

if (LastModified = =-1) {

Servlet doesn ' t support if-modified-since, no reason

To go through further expensive logic

Doget (req, resp);

} Else {

long ifmodifiedsince = Req.getdateheader (header_ifmodsince);

if (Ifmodifiedsince < (lastmodified/1000 * 1000)) {

If The servlet mod time is later, call Doget ()

Round down to the nearest second for a proper compare

A Ifmodifiedsince of-1 would always is less

Maybesetlastmodified (resp, lastmodified);

Doget (req, resp);

} 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 {

//

Note that this means NO servlet supports whatever

method is requested, anywhere on the this server.

//

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);

}

}

ServletRequest with the HttpServletRequest

The former represents the client request parameters, which can be used to read the client request data methods, such as getContentType, Getlocalport and so on.

The latter is a sub-interface of the former, it provides a way to read the relevant information in the HTTP request, such as the query string in the Getmethod,getquerystring,http request,? The content behind.

originally, we had to parse http ourselves . request and then make a response now according to Sun the servlet API to build a servlet , you do not need to implement laborious parsing such as HTTP request, this all has servlets Do it, and seal it to httpservletrequest. object, Servlet only need to call GetXXX method .

Servletresponse and the HttpServletResponse

The former is used to produce the corresponding results, it has a series of setxxx methods to set the response information, the default is Text/plain, save text, servlet through the servletresponse generated HTTP corresponding body part. Binary uses the Getoutputstream method of the servlet to return a Servletoutputstream object to output the binary data, and the Getwrte method returns a Printwrite object that returns the positive for the string form.

The latter is the former sub-interface, through which to set the HTTP response header, write cookies to the client, and so on, AddHeader. Addcookie.

In addition, it has a static state constant.

ServletContext

Is the interface between the servlet and the servlet container, and when the container launches a Web application, it creates a unique ServletContext object that manages the various resources that access the container, 6 methods:

1. A way to share data within a Web application, Setattribute,getattribute

2. Access resources for the current web App

3. Access other web apps in the servlet container. ServletContext getcontext (java.lang.String uripath)

4. Access server-side file system resources, Getrealpath,getresource

5. Output log

6. accessing container-related information


Http://wenku.baidu.com/view/e6f6d184b9d528ea81c779b8.html

ServletContext: For any servlet, anyone works at any time, which is the real global object.

<web-app>
.................
<init-param>
<param-name>charset</param-name>
<param-value>GB2312</param-value>
</init-param>
.................
</web-app>

Java Web the life cycle and Servlet Life cycle

1. Web application: 3 Stage, start phase, run phase, termination phase

A) Start: Load Web. XML--------Create a ServletContext object for the website-----Initialize all filter-----for servlet initialization that needs to be initialized when it starts

b) Run: The most important phase, at which point all servlets are in the standby phase, responding to requests at any time, if the servlet is not initialized, initialize before calling the Servlet method

c) Termination: Destroying the runtime's servlet---destroying the filter-----of the runtime destroys all web App-related objects, such as Servletccotext, and frees the resources that the Web app consumes

2.Servlet life cycle: 3 States, initializing, running, destroying

A initialization The Claa file reads into memory------The servlet container creates servletconfig------contains initialization configuration information for the special Servlet--------container creates a Servlet object----calls the Servlet object's init ( ServletConfig Fig)

If the servlet is first accessed, it is initialized, and if the servlet sets the <load-on-startup> element, the container starts the Servlet app and initializes

B. Run phase response requests

C destroy: When the Web App terminates, the servlet container invokes all the servlet's destory methods before destroying the Servlet objects, and also destroys the servletconfig associated with the servlet.

3.servletcontext and Web Application scope

ServletContext has the same life cycle as Web applications, and the Web application scope represents a time period consisting of the life cycle of a Web application, the collection of all Web Components in the life cycle of a Web application, the sharing of data, and the ability to access the shares within the scope of the WWB application. This can be achieved by ServletContext objects, which is setattribute and Removeattrinut, GetAttribute, and so on.

4.servletcontextlistener listener

Monitoring the life cycle of ServletContext is actually the life cycle of listening to Web applications

contextinitialized, contextdestoryed events, which can be used to implement initialization, destruction, some persistent storage (download/upload/image/....) )

Filter filters

Some of the same actions may be done during the response of some Web components to a customer request, such as checking the IP first, using a filter: Before the Wen component is called, examining the Servicerequest object, modifying the contents of the request header, the request body, or preprocessing the request; filter , you can examine the Servletresponse object after the Wen component is called, modify the response header, and the response body.

HTTP Session

Session Management: In some cases, the container transfers the HttpSession object from memory to the persistent device, which ensures that the pre-restart session can be resumed after the Web app is restarted.

Tomcat currently consists of two ways:

Standard Session Manager: Org.apache.catalina.session.StandardManager

Persistent Session Manager: Org ..... ..... ..... ....... .............. Presistentmanager

The former: When the Tomcat server terminates or the Web application terminates, the HttpSession object of the terminated web app is persisted and saved in the file. Home/work/catalina/hostname/applicationname/sessions.ser. When restarting, activate

The latter: Provides a more flexible function, which httpsession the persistent storage device that holds the object as the session store:

ü When Tomcat is closed or restarted (or a single web), the HttpSession persistence store

U has fault tolerance, then back up to session store to prevent accidental shutdown

ü Flexible control of the number of httpsession in memory

Two implementations:

Filestore, in the file

Jdbcstore: In the database

Listening for sessions

Httpsessionlistener: The creation of a listening session and the destruction of events, as follows two methods,

Sessioncreated (Httpsessionevent event), sessiondestoryed (Httpsessionevent event)

Httpsessionattributelistener: adding, replacing, deleting property events in a listening session

Httpsessionbindinglistener: A listener session is bound to an attribute or unbound event

Httpsessionactivctionlistener: An event that listens to a session being activated or shelved.

The first two must be notified in the Web. xml file that the <listener> element is registered with the container, and the latter two are implemented by the session's properties, assuming that the object of the MyData class is bound as the session's attribute, if you want the listener to be unbound by the conversation binding, And the event that the session is activated or shelved, you can have the MyData class implement the latter two interfaces.

Web Container and Servlet

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.