The life cycle of the servlet and the threading model of the runtime

Source: Internet
Author: User

14th Chapter Life Cycle Note

Talking about the life cycle of the servlet and the threading model of the runtime helps to understand how the servlet works so that some conflicting designs can be avoided.

If you do not meet any of the following conditions, please continue reading, otherwise please skip the next section and go to the following chapter: Chapter 15th, pagination .

    1. Understand the life cycle of the servlet.

    2. Learn about the threading model of the Servlet runtime and the parts to be aware of when designing the program.

14.1. Life cycle

We used to use Javax.servlet.http.HttpServlet, which implements the Javax.servlet.Servlet interface, and the three methods defined in this interface are required by all servlets.

Package Javax.servlet;public interface Servlet {    void init (servletconfig config);    void Service (ServletRequest request, servletresponse response);    void destroy ();}        

, a server such as Tomcat first initializes the servlet based on the definition in Web. XML, then calls its init () method, and the ServletConfig parameter of the init () method is the server passed into the servlet, It contains the initialization information for the Web. XML configuration and shared content such as the ServletContext object.

The initialized servlet instance enters the state of the wait request, and when there is a request that matches the servlet-mapping, the server invokes the service method of the servlet instance. Incoming ServletRequest and servletresponse two parameters wait for the servlet to finish processing.

Note that for each Web application there is only one servlet instance in memory, and all requests call this servlet instance, so we say that the servlet is not thread-safe and that all operations are restricted to the service () method, Do not define class variables in the servlet. (Doget () and Dopost () are auxiliary methods that are branched out after the service () method is overwritten by the httpservlet, in effect the server calls the service (). )

When the web app unloads, the server invokes destroy () for each of the already initialized Servlets, and then destroys the servlet instances, which can be written in the Destory () method if you need to release any resources when the servlet is destroyed.

So when did the servlet initialize? We can pass the load-on-startup tag in Web. Xml.

<servlet>    <servlet-name>TestServlet</servlet-name>    <servlet-class>anni. Testservlet</servlet-class>    <load-on-startup>1</load-on-startup></servlet>        

The value of Load-on-startup is an integer, and when it is greater than or equal to zero, the server initializes the servlet when the Web is published. When it is less than 0 or we do not set Load-on-startup, the server initializes the servlet the first time the user accesses the servlet.

Maybe you have questions about why Load-on-startup is an integer, why not true and false? This is because if we set up multiple Servlets in Web. XML, we can use Load-on-startup to specify the order in which the servlet is loaded, and the server initializes the servlet according to the size of the load-on-startup. But even if we set the Load-on-startup to repeat, there will be no exceptions, and the server will decide the order of initialization itself.

Look back Javax.servlet.Filter also has the init () and Destroy () methods, its declaration period is basically consistent with the servlet, the server uses init () to initialize the filter, when the filter is destroyed call Destroy () method, except that the filter does not have a load-on-startup setting, it is always initialized when the server is started, and then executes sequentially in the order defined by the Web. Xml.

14.2. Threading Model

We do an experiment to prove that some of the methods of writing the servlet are absolutely wrong.

The first step, we open the browser, browse the 14-02 index.jsp page, enter "Ding-dong".

In the second step, we open a 14-02/index.jsp page and enter "Lingirl".

The third step, click on the first page of the Submit button, and then within 10 seconds to click on another page of the submit button, and so on two pages are submitted successfully, we will see the following page.

URL has garbled this is to submit "ding-dong" page, will be surprised? It should have been "ding-dong" at this time.

This page corresponds to the page that submitted "Lingirl" and it appears to be normal.

What is wrong, why the first page submitted the data, but the second page to submit the results, first let's look at the Testservlet code.

Package Anni;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Testservlet extends HttpServlet {    private String username;    public void doget (HttpServletRequest request,                    httpservletresponse response)            throws Servletexception, IOException {        this.username = Request.getparameter ("username");        try {            Thread.Sleep (10000);        } catch (Interruptedexception ex) {        }        response.getwriter (). Write ( This.username);}    }        

The Doget () method obtains the username parameter from the request and assigns it to This.username, which is a class variable. Then pause for 10 seconds, this 10 seconds we assume that some very time-consuming calculations are taking place, so that we have 10 seconds to go to the submit button for two pages. Finally, write this.username to response.

You may be thinking, "This is OK, the first page submits the data, waits 10 seconds to return, the second page submits the data, waits 10 seconds to return, the two does not conflict." "But in fact there is no such queue in the multithreaded model to allow the request to be executed one at a-all requests are swarming."

In this example, the first request came over the "ding-dong" assignment to This.username after the wait, within 10 seconds of our second request called the Doget () method, and the This.username modified to "Lingirl", After waiting 10 seconds after the first request is over, the this.username is already "lingirl".

This.username This notation is absolutely disabled in the servlet, and if there is any information that needs to be saved, consider placing it in the session or ServletContext.

14.3. Defining class Variables in JSPs

The code written between <%%> is run within the service () method after it is converted into a servlet, so we don't have to worry about this.username on top.

But we can define class variables or class methods with <%!%> (notice the extra exclamation), and transform the last heinous servlet into a JSP, like this.

<%@ page contenttype= "text/html; charset=gb2312 "%><%!    String username;%><%    this.username = Request.getparameter ("username");    try {        Thread.Sleep (10000);    } catch (Interruptedexception ex) {    }    out.write (this.username);%>        
Attention

Use the 14-03 example to test the effect of JSP error, remember to click two times within 10 seconds.

<%!%> seems to be a huge trap, and if we use it to define class variables there will be a multithreaded error.

But there are pros and cons, and when we need to define a common approach in JSP, we need to use the power of <%!%>, assuming we need a way to display different HTML content based on the user's gender, and if sex = 0, output the red "male" if sex = 1 is the output of the green "female". To implement this function, we can define a Sexrenderer () method.

The 14-04/index.jsp page displays the following results:

The code in INDEX.JSP is divided into two parts.

The first section defines the Sexrenderer () method and

<%!    Public String sexrenderer (int sex) {        if (sex = = 0) {            return "<span style= ' color:red; ' > Male </span> ";        } else if (sex = = 1) {            return "<span style= ' Color:green; ' > Women </span> ";        } else {            return "";        }    } %>        

The second part loops through the array that holds the gender information, and the Sexrenderer () method is called when the display is displayed.

<%    int[] people = {0, 1, 1, 0};    for (int i = 0; i < this.people.length; i++) {%>                <tr>                    <td><%=this.sexrenderer (this.people[ I])%></td>                </tr><%    }%>        

OK, now we know that we can define methods and variables in <%!%>. However, it is also understood that <%!%> is out of service (), which leads to the inability to use request,response default variables in it, if you want to invoke request can only be written as void DoSomething ( HttpServletRequest request) in the form of a little attention can be.

14.4. JSP nine default objects

The request, response, out, PageContext, session, application, page, config, exception, respectively.

Let's look at their correspondence to the variables in the servlet.

The first thing to make clear is that these nine variables are only valid in <%%>,<%!%> cannot invoke these nine objects. Actually <%%> will eventually become the code in the Service () method, so let's take a look at how to get these objects in the service () method.

  1. Request

    public void Service (ServletRequest req, servletresponse res) {    httpservletrequest request  = ( httpservletrequest) req;}                

    The request in the JSP is the Req parameter passed into the service (), because the service defines the ServletRequest type, and we also need to convert to the HttpServletRequest type.

  2. Response

    public void Service (ServletRequest req, servletresponse res) {    httpservletresponse response  = ( HttpServletResponse) Res;                

    As in the previous example, response is also the RES parameter passed in service ().

  3. Out

    Writer out = Response.getwriter ();                

    Out corresponds to the writer object taken out of the response and is responsible for outputting the data to the response. But there is a little difference between the JSP and the servlet, Although they all implement the Java.io.Writer interface, the actual type in the servlet is Java.io.PrintWriter, and the actual type in the JSP is Javax.servlet.jsp.JspWriter.

  4. PageContext

    This is unique to JSP, the servlet does not have the concept of page.

  5. Session

    HttpSession session = Request.getsession ();                

    Get the session directly from the request.

  6. Application

    Servletconext application = Getservletconfig (). Getservletcontext ();                

    You can get ServletContext through ServletConfig, an object that is shared across the Web App.

  7. Page

    Object page = this;                

    The page represents the current JSP object, or you can use the this reference directly.

  8. Config

    ServletConfig config = Getservletconfig ();                

    This is an object that is passed in by the server at the time of the servlet initialization and can be used to obtain the initialization parameters defined in Web. Xml.

  9. exception

    To use this object in a JSP, you need to meet some conditions.

    First we want to throw an exception in the 14-05/index.jsp.

    <%@ page contenttype= "text/html; charset=gb2312 "errorpage=" error.jsp "%><%    String str = null;    Str.length ();%>                

    The STR value is null, and the length () method directly on the null raise NullPointerException, and we can see that the first line of the page uses the JSP Directive (Directive) to set the Errorpage= "error.jsp", This will automatically forward to error.jsp when an exception occurs. Now look at what's in error.jsp.

    <%@ page contenttype= "text/html; charset=gb2312 "iserrorpage=" true "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "Http://www.w3.org/TR/html4/strict.dtd" >

    The main thing is to set iserrorpage= "true" in the JSP Directive (Directive) so that we can use the exception object in the JSP, which is actually removed from the request.

So far, the JSP nine default objects have been explained, which is commonly used in four scopes corresponding to the object, other understanding can be.

The life cycle of the servlet and the threading model of the runtime

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.