Javaweb Fundamentals (5) _servlet principle

Source: Internet
Author: User
Tags tomcat server

I. Introduction of the Servlet

The servlet is a technology that Sun offers to develop dynamic Web resources.
In its API, Sun provides a servlet interface that users want to use to send a dynamic Web resource (that is, to develop a Java program to output data to a browser), the following 2 steps need to be completed:
1. Write a Java class to implement the Servlet interface.
2. Deploy the well-developed Java class to the Web server.
In accordance with a customary salutation, we often refer to Java programs that implement a servlet interface, called a servlet

Second, the operation of the servlet process

The servlet program is called by the Web server after the Web server receives a servlet access request from the client:
The ①web server first checks to see if the instance object for the servlet has been loaded and created. If it is, execute step ④ directly, otherwise, step ②.
② mounts and creates an instance object of the servlet.
③ invokes the Init () method of the Servlet instance object.
④ creates a HttpServletRequest object that encapsulates the HTTP request message and a HttpServletResponse object that represents the HTTP response message, and then calls the servlet's service () Method and passes the request and response objects in as parameters.
Before the ⑤web application is stopped or restarted, the servlet engine uninstalls the servlet and calls the servlet's Destroy () method before uninstalling.

Third, servlet call graph


Iv. developing a servlet in eclipse

To create a new Web project project in Eclipse, Eclipse automatically creates the directory structure as shown:


4.1. Servlet interface Implementation Class

Servlet Interface Sun Company defines two default implementation classes, namely: Genericservlet, HttpServlet.

HttpServlet refers to a servlet capable of handling HTTP requests, which adds some and HTTP protocol processing to the original servlet interface, which is more powerful than the servlet interface. As a result, developers should typically inherit this class when writing a servlet, rather than implementing the Servlet interface directly.
HttpServlet when implementing the Servlet interface, the service method is covered, and the code in the body of the method automatically determines how the user is requested, such as a GET request, and calls the HttpServlet Doget method, such as a POST request, to invoke the Dopost method. As a result, developers usually need to overwrite the Doget or Dopost method when writing a servlet, rather than overwrite the service method.

4.2. Creating and writing Servlets through eclipse

Select the package, right-→new→servlet, as shown in:




In this way, we create a servlet with the good one name ServletDemo1 through Eclipse, creating a good ServletDemo01 with the following code:

 1 package; 2 3 Import; 4 Import; 5 6 Import Javax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest;      9 Import javax.servlet.http.httpservletresponse;10 One public class ServletDemo1 extends HttpServlet {12 13/**14 * The Doget method of the servlet. <br>15 *16 * This method was called when a form have its tag value method equals to get.17 * 18 * @param request the request send by the client to the SERVER19 * @param response The response send by the server to th E client20 * @throws servletexception If an error occurred21 * @throws IOException If an error occurred22 *  /23 public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception,         IOException {response.setcontenttype ("text/html"); PrintWriter out = Response.getwriter (); 28 OuT.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > "); Out.println (" <HTML> ");         . println ("

The code is automatically generated by Eclipse, and the Web. xml file also has more <servlet></servlet> and <servlet-mapping></servlet-mapping > Two pairs of labels, these two pairs of tags are configured ServletDemo1, as shown in:

Then we can access the ServletDemo1 servlet through the browser, as shown in:


V. Servlet Development Note Details 5.1, servlet access URL mapping configuration

Because the client accesses the resources in the Web server through a URL address, the servlet program must map the servlet program to a URL address if it wants to be accessed by the outside world, and this works with the <servlet> element and < in the. xml file The servlet-mapping> element is complete.
The <servlet> element is used to register a servlet, which contains two primary child elements:<servlet-name> and <servlet-class> Used to set the registration name of the servlet and the full class name of the servlet, respectively.
An <servlet-mapping> element is used to map an external access path to a registered servlet, which contains two child elements:<servlet-name> and <url-pattern> Used to specify the name of the servlet's registry and the external access path of the servlet, respectively. For example:

1   <servlet>2     <servlet-name>servletdemo1</servlet-name>3     <servlet-class></servlet-class>4   </servlet>5 6   <servlet-mapping>7     <servlet-name>servletdemo1</servlet-name>8     <url-pattern>/servlet/servletdemo1</ Url-pattern>9   </servlet-mapping>

The same servlet can be mapped to multiple URLs, that is, the set value of the <servlet-name> child elements of multiple <servlet-mapping> elements can be the registered name of the same servlet. For example:

1 <servlet> 2 <servlet-name>ServletDemo1</servlet-name> 3 <servlet-class></servlet-class> 4 </servlet& Gt 5 6 <servlet-mapping> 7 <servlet-name>ServletDemo1</servlet-name> 8 <url-pattern>/servlet/servletdemo1</url-pattern> 9 </servlet-mapping>10 <servlet-mapping>11<Servlet-name>ServletDemo1</servlet-name>12 <url-pattern>/1.htm</url-pattern>13 </servlet-mapping>14 <servlet-mapping>15 <servlet-name>ServletDemo1</servlet-name>16 <url-pattern>/2.jsp</url-pattern>17 </servlet-mapping>18 <servlet-mapping>19 <servlet-name>ServletDemo1</servlet-name>20 <url-pattern>/3.php</url-pattern>21 </servlet-mapping>22 <servlet-mapping>23 <servlet-name>ServletDemo1</servlet-name>24 <url-pattern>/4.aspx</url-pattern>25 </servlet-mapping>

With the above configuration, when we want to access a servlet with the name ServletDemo1, we can use several addresses to access:






The SERVLETDEMO1 is mapped to multiple URLs.

5.2. servlet access URL using * wildcard mapping

You can also use the * wildcard character in the URL that the servlet maps to, but there can be only two fixed formats: one format is "*. Extension" and the other is preceded by a forward slash (/) and ends with "/*" . For example:


1  <servlet>2     <servlet-name>servletdemo1</servlet-name>3     <servlet-class></servlet-class>4   </servlet>5 6    <servlet-mapping>7     <servlet-name>servletdemo1</servlet-name>8    <url-pattern>/*</url-pattern>

* can match any character, so at this point you can use any URL to access the ServletDemo1 servlet, as shown in:


For some of the following mapping relationships:
Servlet1 Mapping to/abc/*
Servlet2 Map to/*
Servlet3 Mapping to/ABC
Servlet4 Mapping to *.do
When the request URL is "/abc/a.html", "/abc/*" and "/*" match, which Servlet responds
The servlet engine calls Servlet1.
When the request URL is "/ABC", both "/abc/*" and "/ABC" match, which Servlet responds
The servlet engine calls Servlet3.
When the request URL is "/abc/", both "/abc/*" and "*.do" match, which Servlet responds
The servlet engine calls Servlet1.
When the request URL is "/", "/*" and "*.do" match, which Servlet responds
The servlet engine calls Servlet2.
When the request URL is "/xxx/yyy/", "/*" and "*.do" match, which Servlet responds
The servlet engine calls Servlet2.
  The principle of matching is, "who looks more like who's looking?"

5.3. The difference between servlet and common Java class


Servlet is a Java class that is called by other Java programs (servlet engines) and cannot run independently, and it is run entirely by the servlet engine to control and dispatch.
multiple servlet requests for the client, typically, the server creates only one Servlet instance object, that is, once the Servlet instance object is created, it resides in memory and serves subsequent requests until the Web container exits. The servlet instance object will not be destroyed.
The servlet's Init method is called only once throughout the servlet's life cycle. Each access request to a servlet causes the servlet engine to invoke the Servlet's service method once. For each access request, the Servlet engine creates a new HttpServletRequest request object and a new HttpServletResponse response object. The two objects are then passed as arguments to the service () method of the servlet that it invokes, and the service method calls the Doxxx method separately, depending on the request.

If a <load-on-startup> element is configured in the <servlet> element, the Web application loads and creates an instance object of the servlet at startup, and the Init () method that invokes the Servlet instance object.

Purpose: Write a initservlet for the Web application, which is configured to mount at boot time, creating the necessary database tables and data for the entire Web application.

5.4. Default servlet

If a servlet's mapping path is just a forward slash (/), the servlet becomes the default servlet for the current Web application.
The URL of a matching <servlet-mapping> element cannot be found in the Web. xml file, and their access requests are given to the default servlet processing, that is, the default servlet is used to handle access requests that are not handled by all other servlets. For example:

1  <servlet> 2     <servlet-name>ServletDemo2</servlet-name> 3     <servlet-class></servlet-class> 4     <load-on-startup>1</load-on-startup> 5   </servlet> 6    7   <!--Configure ServletDemo2 as the default servlet--8   <servlet-mapping> 9     < SERVLET-NAME>SERVLETDEMO2</SERVLET-NAME>10     <url-pattern>/</url-pattern>11   </servlet-mapping>

When accessing a servlet that does not exist, it is processed using the configured default Servlet, as shown in:


installation directory in <tomcat >\conf\ Web. xml file, a servlet named Org.apache.catalina.servlets.DefaultServlet is registered, and the servlet is set to the default servlet.

1     <servlet> 2         <servlet-name>default</servlet-name> 3         <servlet-class >org.apache.catalina.servlets.DefaultServlet</servlet-class> 4         <init-param> 5             <param-name>debug</param-name> 6             <param-value>0</param-value> 7         </init-param > 8         <init-param> 9             <param-name>listings</param-name>10             <param-value> False</param-value>11         </init-param>12         <load-on-startup>1</load-on-startup>13     </servlet>14  <!--the mapping for the default servlet-->16     <servlet-mapping>17< c17/><servlet-name>default</servlet-name>18         <url-pattern>/</ url-pattern>19     </servlet-mapping>

When accessing a static HTML file and picture in a Tomcat server, you are actually accessing the default servlet.

5.5. Thread Safety for Servlets

When multiple clients access the same servlet concurrently, the Web server creates a thread for each client's access request and invokes the Servlet's service method on that thread, so if the same resource is accessed within the service method, It is possible to raise a thread safety issue. For example, the following code:

There is no code for thread safety issues:

 1 package; 2 3 Import; 4 5 Import Javax.servlet.ServletException; 6 Import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse; 9 public class ServletDemo3 extends HttpServlet {One to ten public void doget (HttpServletRequest request, Httpser Vletresponse response) throws Servletexception, IOException {15 16/**17 * When multithreading concurrent access Is there a thread-safety problem with the code inside this method? * I variables are accessed concurrently by multiple threads, but there is no thread safety problem because I is a local variable inside the Doget method, 19 * When there are multiple threads concurrently accessing the Doget method, each thread has its own I variable, 20 * Each thread operates its own I variable, so there is no thread safety issue 21 * Multithreading concurrent access to a method, if some resources (variables, collections, etc.) are defined within the method 22 * Then each thread has this     Something, so there is no thread safety issue. */24 int i=1;25 i++;26 response.getwriter (). write (i); 27}28 29 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex ception {DoGet (request, response); 32}33 34} 

Code that has thread safety issues:

1 package; 2  3 import; 4  5 import javax.servlet.ServletException; 6 import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse;  9 public class ServletDemo3 extends HttpServlet {One to ten     int i=1;13 public     void doget (HttpServletRequest request, HttpServletResponse response)             throws Servletexception, IOException {i++;17         try {             Thread.Sleep (1000*4);         catch (Interruptedexception e) {             e.printstacktrace ();         }22         Response.getwriter (). Write (i+ "");     }24 public     void DoPost (HttpServletRequest request, HttpServletResponse response)             throws Servletexception, IOException {         doget (request, response); 28     }29 30}

Define I as a global variable, when multiple threads concurrently access the variable I, there will be a thread safety problem, as shown: Open two browser simultaneously to simulate concurrent access to the same servlet, the first browser should normally see 2, and the second browser should see 3, As a result, two browsers see 3, which is not normal.


A thread-safety problem exists only when multiple threads concurrently operate the same resource, so when you write a servlet, there is a thread-safety problem with concurrent access to a resource (variables, collections, etc.), so how do you solve this problem?

First look at the following code:

 1 package; 2 3 Import; 4 5 Import Javax.servlet.ServletException; 6 Import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse; 9 public class ServletDemo3 extends HttpServlet {ten int i=1;14 public void doget (HttpServletRequest reque St, httpservletresponse response) throws Servletexception, IOException {16/**17 * plus SYNCHR After onized, there is no thread safety problem when I am concurrently accessing I, 18 * Why is there no thread safety problem after adding synchronized?          19 * If there is a thread accessing the Servlet object now, it will first get the lock of the Servlet object 20 * Wait until it finishes executing before returning the lock back to the Servlet object, because it first gets the Servlet object's lock, 21 * So when there are other threads accessing the Servlet object, because the lock has been taken away by the previous thread, the thread behind it can only wait for the */24 synchronized (this) {//             In Java, each object has a lock, here is the Servlet object i++;26 try {thread.sleep (1000*4); 28 } catch (Interruptedexception e) {E.printstackTrace ();}31 response.getwriter (). Write (i+ "");}33}35, public vo          ID doPost (httpservletrequest request, httpservletresponse response) Notoginseng throws Servletexception, IOException {38 Doget (request, response); 39}40 41}

This is now done by adding a lock to the Servlet object to ensure that only one thread accesses the resource within the Servlet object at any time, so there is no thread-safety issue, as shown in:


This approach solves the thread-safety problem, but writing a servlet is no way to deal with thread safety, and if 9,999 people visit the servlet at the same time, then the 9,999 must queue in turn.

For servlet thread-safety issues, Sun is offering a solution: let the servlet implement a Singlethreadmodel interface, if a servlet implements the Singlethreadmodel interface, The servlet engine will then invoke its service method in single-threaded mode.
Looking at the API of Sevlet, you can see that there are no methods and constants defined in the Singlethreadmodel interface, in Java, an interface that does not define any methods and constants is called a labeled Interface , and one of the most typical markup interfaces that is often seen is " Serializable", this interface also does not define any methods and constants, what is the use of the markup interface in Java? The main function is to give an object a flag, tell the JVM, what this object can do, such as the implementation of the "Serializable" Interface class object can be serialized, there is a "cloneable" interface, this is a token interface, By default, objects in Java are not allowed to be cloned, like real-life people do not allow cloning, but as long as the implementation of the "Cloneable" interface, then the object can be cloned.

Let the servlet implement the Singlethreadmodel interface, as long as the definition of the servlet class is added to implement the Singlethreadmodel interface declaration.
  The Servlet,servlet engine, which implements the Singlethreadmodel interface, still supports multithreaded concurrent access to the servlet by producing multiple servlet instance objects. Each concurrent thread invokes a separate Servlet instance object .
Implementing the Singlethreadmodel interface does not really address the thread safety of the servlet, because the servlet engine creates multiple servlet instance objects. The real problem with multithreading security is that a Servlet instance object is called simultaneously by multiple threads. In fact, in servlet API 2.4, Singlethreadmodel has been marked as deprecated (obsolete).

Javaweb Fundamentals (5) _servlet principle

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: 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.