In-depth analysis of Java Web Item5-Servlet Development
1. Servlet Introduction
Servlet is a technology provided by sun for developing dynamic web resources.
Sun provides a servlet interface in its API. To send a dynamic web Resource (that is, to develop a Java program to output data to the browser), follow these two steps:
1. Compile a Java class to implement the servlet interface.
2. Deploy the developed Java class to the web server.
According to a conventional naming convention, we usually call the java program that implements the servlet interface Servlet
Ii. Servlet running process
The Servlet program is called by the WEB server. After the web server receives the Servlet access request from the client:
① The Web server first checks whether the Servlet instance object has been loaded and created. If yes, perform Step 4. Otherwise, perform step 2.
② Load and create an instance object for the Servlet.
③ Call the init () method of the Servlet instance object.
④ Create an HttpServletRequest object that encapsulates the HTTP request message and an HttpServletResponse object that represents the HTTP Response Message. Then call the Servlet service () method and pass the request and response object as parameters.
⑤ Before the WEB application is stopped or restarted, the Servlet engine will uninstall the Servlet and call the Servlet's destroy () method before uninstalling it.
3. Servlet call Diagram
Servlet call Diagram
4. Develop Servlet in Eclipse
Create a new web project in eclipse. eclipse automatically creates the directory structure shown in:
4.1 Servlet interface implementation class
Servlet interface SUN defines two default implementation classes:GenericServlet
,HttpServlet
.
HttpServlet is a servlet that can process HTTP requests. It adds some HTTP protocol processing methods to the original Servlet interface. It is more powerful than the Servlet interface. Therefore, when writing a Servlet, developers should generally inherit this class, instead of directly implementing the Servlet interface.
When HttpServlet implements the Servlet interface, it overwrites the service method. The code in this method automatically determines the user's request method. For example, if it is a GET request, it calls the doGet method of HttpServlet, for a Post request, the doPost method is called. Therefore, when writing a Servlet, developers generally only need to override the doGet or doPost method, rather than the service method.
4.2 create and compile a Servlet through Eclipse
Select the gacl. servlet. study package, right-click → New → Servlet, as shown in:
In this way, we can use Eclipse to create a Servlet named ServletDemo1. The following code is provided in the created 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;public class ServletDemo1 extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("
"); Out. println (" "); Out. println ("
"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println("
"); Out. println ("
"); out.flush(); out.close(); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("
"); Out. println (" "); Out. println ("
"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println("
"); Out. println ("
"); out.flush(); out.close(); } }
These codes are automatically generated by Eclipse, andweb.xml
Too many files
And
Two pairs of tags, which are configuredServletDemo1
, As shown in:
Then we can accessServletDemo1
ThisServlet
, As shown in:
5. Servlet development considerations
5.1 configure Servlet URL ing
Because the client accesses resources on the web server through the URL address, if the Servlet program is to be accessed by the outside world, the servlet program must be mapped to a URL address, which works on the web. use in xml files
Element and
Element complete.
An element is used to register a Servlet. It contains two main child elements:
And
Set the Registration Name of the Servlet and the complete Class Name of the Servlet respectively.
One
The element is used to map an external access path of a registered Servlet. It contains two sub-elements:
And
To specify the Registration Name of the Servlet and the external access path of the Servlet. For example:
ServletDemo1
gacl.servlet.study.ServletDemo1
ServletDemo1
/servlet/ServletDemo1
ServletDemo1
gacl.servlet.study.ServletDemo1
ServletDemo1
/servlet/ServletDemo1
ServletDemo1
/1.htm
ServletDemo1
/2.jsp
ServletDemo1
/3.php
ServletDemo1
/4.ASPX
Through the above configuration, when we want to access the Servlet named 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
ServletDemo1 is mapped to multiple URLs.
5.2 use * wildcard ing for Servlet access URLs
You can also useWildcard, but there can only be two fixed formats: one format is". Extension ". The other format starts with a forward slash (/) and ends.For example:
ServletDemo1
gacl.servlet.study.ServletDemo1
ServletDemo1
/*
*
It can match any character, so you can use any URL to access the Servlet ServletDemo1, as shown in:
For the following mappings:
Serving Servlet1
/abc/*
Serving Servlet2
/*
Serving Servlet3
/abc
Serving Servlet4
*.do
Problem:
When the request URL is"/abc/a.html
","/abc/*
And“/*”
Which servlet response is matched?
The Servlet Engine calls Servlet1.
When the request URL is“/abc”
,“/abc/*”
And“/abc”
Which servlet response is matched?
The Servlet Engine calls Servlet3.
When the request URL is“/abc/a.do”
,“/abc/*”
And“*.do”
Which servlet response is matched?
The Servlet Engine calls Servlet1.
When the request URL is"/a.do”
,“/*”
And“*.do”
Which servlet response is matched?
The Servlet Engine calls Servlet2.
When the request URL is“/xxx/yyy/a.do”
,“/*”
And“*.do”
Which servlet response is matched?
The Servlet Engine calls Servlet2.
The matching principle is "Who looks more like who is looking"
5.3 Servlet Lifecycle
Servlet is a Java class called by other Java programs (Servlet Engine). It cannot run independently. Its running is controlled and scheduled by the Servlet engine.
For multiple Servlet requests from the client, the server usually creates only one Servlet instance object. That is to say, once the Servlet instance object is created, it will reside in the memory, for other subsequent request services, the servlet instance object will not be destroyed until the web Container exits.
During the entire Servlet lifecycle, the Servlet init method is called only once. Each access request to a Servlet causes the Servlet engine to call the servlet service method once. For each access request, the Servlet engine will create a new HttpServletRequest request object and a new HttpServletResponse response object, and then pass these two objects as parameters to the Servlet service () It calls () the service method then calls the doXXX Method Based on the Request Method.
If
An
When the WEB application starts, it loads and creates the Servlet Instance Object and calls the init () method of the Servlet instance object.
Example:
invoker
org.apache.catalina.servlets.InvokerServlet
1
Purpose: Write an InitServlet for a web application. This servlet is configured to start the loading and create necessary database tables and data for the entire web application.
5.4 default Servlet
If the Servlet ing path of a Servlet is only a forward slash (/
), Then this Servlet becomes the default Servlet of the current Web application.
Allweb.xml
File cannot find matching
Element URL. All access requests are sent to the default Servlet. That is, the default Servlet is used to process access requests that are not processed by all other servlets. For example:
ServletDemo2
Gacl. servlet. study. ServletDemo2
1
ServletDemo2
/
When accessing a non-existent Servlet, use the configured default Servlet for processing, as shown in:
In \ Conf \ web. xml
File, registered with a nameZ role? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> trim + trim" brush: java; "> default org.apache.catalina.servlets.DefaultServlet debug 0 listings false 1 default /
When accessing a static HTML file and image on the Tomcat server, the default Servlet is actually accessed.
5.5. Servlet thread security issuesWhen multiple clients concurrently access the same Servlet, the web server creates a thread for each client's access request and calls the Servlet service method on this thread, therefore, if the same resource is accessed in the service method, thread security problems may occur. For example, the following code:
Code without thread security 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 multiple threads concurrently access the code in this method, is there a thread security problem? * I variables are accessed by multiple threads concurrently, but there is no thread security problem, because I is a local variable in the doGet method, * When multiple threads concurrently access the doGet method, each thread has its own I variable. * Each thread operates on its own I variable, so there is no thread security problem * when multiple threads concurrently access a method, if some resources (variables, sets, etc.) are defined in the Method *, each thread has these things, so there is no thread security problem */int I = 1; I ++; response. getWriter (). write (I);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
Code with thread security problems:
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); }}
Seti
Defined as a global variable. When multiple threads concurrently access variable I, there will be thread security issues, as shown in: simultaneously enabling two browsers to simulate concurrent access to the same Servlet, normally, the first browser should see 2, and the second browser should see 3. As a result, both browsers see 3, which is not normal.
Thread security issues only occur when multiple threads concurrently operate on the same resource. Therefore, when writing a Servlet, if you concurrently access a resource (variables, sets, etc ), there will be thread security issues, So how should we solve this problem?
Let's take a 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 {/*** added After synchronized, thread security issues do not exist during concurrent access to I. * why is there no thread security problem after synchronized is added? * If a thread accesses the Servlet object, it will first get the lock of the Servlet object * It will return the lock to the Servlet object after it is executed, because it first gets the lock of the Servlet object, * when other threads access this Servlet object, because the lock has been taken away by the previous thread, the following threads can only wait in queue **/synchronized (this) {// in java, each object has a lock. Here this refers to 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 );}}
In Java, interfaces that do not define any methods and constants are called Mark interfaces. The most typical mark interface that is often seen is "Serializable ", this interface does not define any methods and constants. What is the purpose of marking interfaces in Java? The main function is to mark an object and tell JVM what it can do. For example, the object of the class that implements the "Serializable" interface 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, cloning is not allowed, but as long as the "Cloneable" interface is implemented, the object can be cloned.
Let the Servlet implement the SingleThreadModel interface. You only need to add a Declaration to implement the SingleThreadModel interface in the Servlet class definition.
For servlets that implement the SingleThreadModel interface, the Servlet engine still supports multi-threaded concurrent access to the Servlet. The method used is to generate multiple Servlet instance objects, each concurrent thread calls an independent Servlet instance object.
Implementing the SingleThreadModel interface does not really solve the Servlet thread security problem, because the Servlet engine creates multiple Servlet instance objects, to solve the multi-thread security problem, 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 ).