Javaweb servlet Development Summary (i) _java

Source: Internet
Author: User
Tags http request sleep tomcat server

A brief introduction of the servlet

The servlet is a technology offered by Sun to develop dynamic Web resources.
In its API, Sun provides a servlet interface that requires the following 2 steps to be completed if users want to use a Dynamic Web resource (that is, to develop a Java program to output data to the browser):
1. Write a Java class to implement the Servlet interface.
2, the development of a good Java class deployed to the Web server.
In accordance with a customary salutation, we usually also implement the Servlet interface Java program, called the servlet

Second, the operation of the servlet process

The servlet program is invoked by the Web server, and the Web server receives the client's servlet access request:
The ①web server first checks to see if the Servlet's instance object has been loaded and created. If so, perform the ④ step directly, otherwise, perform step ②.
② loads and creates an instance object for 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 unloads the servlet and calls the servlet's Destroy () method before uninstalling.

Third, the servlet call graph

Iv. developing a servlet in eclipse

When you create a new Web project project in Eclipse, Eclipse automatically creates the directory structure shown in the following illustration:

4.1, the Servlet interface implementation class

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

HttpServlet refers to the servlet that handles HTTP requests, adding some HTTP protocol processing methods 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 and avoid directly implementing the Servlet interface.
HttpServlet when implementing the Servlet interface, the service method is overridden, and the code inside 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 the Dopost method. As a result, when writing a servlet, developers usually only need to override the Doget or Dopost methods, rather than overwrite the service method.

4.2. Creating and writing servlet through eclipse

Select the Gacl.servlet.study package, right-click →new→servlet, as shown in the following figure:

  

  

  

In this way, we create a servlet named ServletDemo1 through Eclipse, and the following code is created inside the ServletDemo01:

Package gacl.servlet.study;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; The public class ServletDemo1 extends HttpServlet {/** * The Doget method is the servlet. <br> * * This met
   Hod is called when a form, has its tag value, equals to get. * @param request the request send by the "client to the" server * @param response the response send by the server T o the client * @throws servletexception If an error occurred * @throws IOException If a error occurred * * Publ

    IC void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
    Response.setcontenttype ("text/html");
    PrintWriter out = Response.getwriter (); Out.println ("<!
    DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">"); Out.prIntln ("<HTML>");
    Out.println (" 

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

We can then access the ServletDemo1 servlet through the browser, as shown in the following illustration:

Five, servlet development attention to detail

5.1. servlet Access URL mapping configuration

Because the client accesses the resources in the Web server through the URL address, the servlet program must map the servlet program to a URL address, using the <servlet> element and < in the Web.xml file, if it wants to be accessed by the outside world. servlet-mapping> element Complete.
The <servlet> element is used to register the servlet, which contains two main 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.
A <servlet-mapping> element is used to map an external access path to a registered servlet that contains two child elements:<servlet-name> and <url-pattern> Used to specify the registration name of the servlet and the external access path of the servlet. For example:

<servlet> <servlet-name>ServletDemo1</servlet-name> <servlet-class> gacl.servlet.study.servletdemo1</servlet-class> </servlet> <servlet-mapping> <servlet-name >ServletDemo1</servlet-name> <url-pattern>/servlet/ServletDemo1</url-pattern> </ Servlet-mapping> the same servlet can be mapped to multiple URLs, that is, the <servlet-name> of multiple <servlet-mapping> elements The setting value of a child element can be the registered name of the same servlet. Example: <servlet> <servlet-name>ServletDemo1</servlet-name> <servlet-class> gacl.servlet.study.servletdemo1</servlet-class> </servlet> <servlet-mapping> <servlet-name >ServletDemo1</servlet-name> <url-pattern>/servlet/ServletDemo1</url-pattern> </ servlet-mapping> <servlet-mapping> <servlet-name>ServletDemo1</servlet-name> <url-pattern >/1.htm</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>servletdemo1 </servlet-name> <url-pattern>/2.jsp</url-pattern> </servlet-mapping> <servlet-mapping> & Lt;servlet-name>servletdemo1</servlet-name> <url-pattern>/3.php</url-pattern> </ servlet-mapping> <servlet-mapping> <servlet-name>ServletDemo1</servlet-name> <url-pattern

 >/4.ASPX</url-pattern> </servlet-mapping>

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

  Http://localhost:8080/JavaWeb_Servlet_Study_20140531/servlet/ServletDemo1

Http://localhost:8080/JavaWeb_Servlet_Study_20140531/1.htm

http://localhost:8080/JavaWeb_Servlet_Study_20140531/2.jsp

http://localhost:8080/JavaWeb_Servlet_Study_20140531/3.php

Http://localhost:8080/JavaWeb_Servlet_Study_20140531/4.ASPX

The ServletDemo1 is mapped to more than one URL.

5.2. The servlet access URL uses the * wildcard character mapping  

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

<servlet>
  <servlet-name>ServletDemo1</servlet-name>
  <servlet-class> gacl.servlet.study.servletdemo1</servlet-class>
 </servlet>

  <servlet-mapping>
  <servlet-name>ServletDemo1</servlet-name>
  <url-pattern>/*</url-pattern>

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

For some of the following mapping relationships:
Servlet1 Map to/abc/*
Servlet2 Map to/*
Servlet3 Map to/abc
Servlet4 Map to *.do
Problem:
When the request URL is "/abc/a.html", "/abc/*" and "/*" are matched, which Servlet responds
The servlet engine will invoke Servlet1.
When the request URL is "/ABC", both "/abc/*" and "/ABC" match, which Servlet responds
The servlet engine will invoke Servlet3.
When the request URL is "/abc/a.do", both "/abc/*" and "*.do" match, which Servlet responds
The servlet engine will invoke Servlet1.
When the request URL is "/a.do", both "/*" and "*.do" match, which Servlet responds
The servlet engine will invoke Servlet2.
When the request URL is "/xxx/yyy/a.do", both "/*" and "*.do" match, which Servlet responds
The servlet engine will invoke Servlet2.
The principle of matching is "who looks more like the one who wants it"

5.3. The difference between a servlet and a normal Java class 

A servlet is a Java class that is invoked by other Java programs (servlet engines), which cannot run independently, and is run entirely by the servlet engine to control and schedule.
For multiple servlet requests to the client, the server typically 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 is not destroyed.
During the entire lifecycle of the servlet, the servlet's Init method is invoked only once. Each access request to a servlet causes the servlet engine to invoke a Servlet's service method. 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 the instance object of the servlet and the Init () method that invokes the Servlet instance object when it starts.
Example:

<servlet>
    <servlet-name>invoker</servlet-name>
    <servlet-class>
      Org.apache.catalina.servlets.InvokerServlet
    </servlet-class>
    <load-on-startup>1</ Load-on-startup>
  </servlet>

Purpose: Write a initservlet for Web applications that are configured to load at startup and create 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 is not found in the Web.xml file, and their access requests are processed by the default servlet, which means that the default servlet is used to handle access requests that are not processed by all other servlet. For example:

<servlet>
  <servlet-name>ServletDemo2</servlet-name>
  <servlet-class> Gacl.servlet.study.servletdemo2</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <!--configure ServletDemo2 as default servlet-->
 <servlet-mapping>
  < servlet-name>servletdemo2</servlet-name>
  <url-pattern>/</url-pattern>
 </ Servlet-mapping>

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

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

<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class> org.apache.catalina.servlets.defaultservlet</servlet-class>
    <init-param>
      <param-name >debug</param-name>
      <param-value>0</param-value>
    </init-param>
    < init-param>
      <param-name>listings</param-name>
      <param-value>false</param-value >
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

 <!--the mapping for the default servlet-->
  <servlet-mapping>
    <servlet-name> default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

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

5.5. Thread-safety issues with the servlet

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

Code that does not have thread safety issues:

Package gacl.servlet.study;

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 ServletDemo3 extends HttpServlet {public

  
  void doget (HttpServletRequest request, HttpServletResponse Response)
      throws Servletexception, IOException {
    
    /**
     * When multithreading concurrently accesses the code inside this method, is there a thread-safety problem?
     I variables are accessed concurrently by multiple threads, but there is no thread-safety problem, because I is a local variable in the Doget method,
     * When multiple threads have concurrent access to the Doget method, each thread has its own I variable,
     * Each thread operates its own I variable, So there is no thread-safety problem
     * Multithreading concurrent access to a method, if some resources (variables, sets, etc.) are defined within the method
     * Then every thread has these things, so there is no thread safety problem. */
    int I=1 ;
    i++;
    Response.getwriter (). write (i);

  public void DoPost (HttpServletRequest request, httpservletresponse response)
      throws Servletexception, IOException {
    doget (request, response);
  }

}

Code that has thread-safety issues:

Package gacl.servlet.study;

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 ServletDemo3 extends HttpServlet {

  int i=1;
  public void doget (HttpServletRequest request, httpservletresponse response)
      throws Servletexception, IOException {
    
    i++;
    try {
      thread.sleep (1000*4);
    } catch (Interruptedexception e) {
      e.printstacktrace ();
    }
    Response.getwriter (). Write (i+ "");

  public void DoPost (HttpServletRequest request, httpservletresponse response)
      throws Servletexception, IOException {
    doget (request, response);
  }

}

To define I as a global variable, when multiple threads have concurrent access to the variable I, there is a thread-safety problem, as shown in the following illustration: Opening two browsers to simulate concurrent access to the same servlet, normally, the first browser should see 2, and the second browser should see 3 of the As a result, two browsers saw 3, which is not normal.

Thread safety issues exist only when multiple threads concurrently operate the same resource, so how do you solve this problem when writing a servlet, if you have concurrent access to a resource (a variable, a collection, etc.) that has a thread-safety problem?

Let's look at the following code:

Package gacl.servlet.study;

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 ServletDemo3 extends HttpServlet {int i=1;
    public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
     /** * After adding synchronized, there is no thread safety problem with concurrent access I, why is there no thread safety problem after adding synchronized? * If a thread now accesses the Servlet object, it first gets the lock on the Servlet object and waits until it finishes executing the lock back to the Servlet object, because it first gets the lock on the Servlet object, * So when there are other threads accessing the SER
      Vlet object, because the lock has been taken away by the previous thread, the following thread can only wait in line */synchronized (this) {//In Java, each object has a lock, here is the Servlet object
      i++;
      try {thread.sleep (1000*4);
      catch (Interruptedexception e) {e.printstacktrace ();
    } response.getwriter (). Write (i+ ""); } public void DoPost (HttpServletRequest request, HTTPSERVLETRESPONSE response) throws Servletexception, IOException {doget (request, response);

 }

}

The practice now is to add a lock to the Servlet object to ensure that only one thread accesses the resources in the Servlet object at any time, so there is no thread-safety problem, as the following illustration shows:

While this approach solves thread-safety issues, writing a servlet cannot handle thread-safety problems in this way, and if 9,999 people access the servlet at the same time, then the 9,999 must be queued for alternate access sequentially.

For the servlet's thread-safety issues, Sun offers 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 Sevlet API, you can see that no methods and constants are defined in the Singlethreadmodel interface, in Java, the interface that does not define any method and constant is called a tag interface, and one of the most typical markup interfaces that is often seen is "Serializable" , and this interface does not define any methods and constants, what is the use of markup interfaces in Java? The main role is to give an object a logo, tell the JVM, what the object can do, such as the implementation of the "Serializable" interface of the class object can be serialized, there is also a "cloneable" interface, which is also a tag interface, by default, Objects in Java are not allowed to be cloned, just as in real life people do not allow cloning, but as long as the "cloneable" interface is implemented, the object can be cloned.

The

enables the servlet to implement the Singlethreadmodel interface, as long as the declaration of implementing the Singlethreadmodel interface is added to the definition of the servlet class.  
The Servlet,servlet engine, which implements the Singlethreadmodel interface, still supports multithreaded concurrent access to the servlet by generating multiple servlet instance objects. Each of the concurrent threads invokes a separate Servlet instance object, respectively. The
implementation of the Singlethreadmodel interface does not really solve the thread-safety problems 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 by multiple threads at the same time. In fact, in servlet API 2.4, Singlethreadmodel has been marked as deprecated (obsolete).
The above is the entire content of this article, I hope to help you learn.

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.