Summary of Java Web servlet development (I)

1、 Introduction to Servlet

Servlet is a technology provided by Sun company for developing dynamic web resources. Sun provides a servlet interface in its API. If users want to send a dynamic web resource (that is, develop a java program to output data to the browser), they need to complete the following two steps: 1. Write a Java class to implement the servlet interface. 2. Deploy the developed Java classes to the web server. According to a conventional calling habit, we usually call the Java program that implements the servlet interface servlet

2、 Running process of Servlet

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, execute step ④ directly; otherwise, execute step ②. ② load and create an instance object of the servlet. ③ call init () method of servlet instance object. Create a HttpServletRequest object for encapsulating the HTTP request message and a HttpServletResponse object representing the HTTP response message, then invoke the service () method of Servlet and pass the request and response object as a parameter. (5) before the WEB application is stopped or restarted, the Servlet engine will unload Servlet and invoke the destroy () method of Servlet before unloading.

3、 Servlet call graph

4、 Developing servlets in eclipse

Create a new web project project in eclipse, and eclipse will automatically create the directory structure shown in the following figure:

4.1. Servlet interface implementation class

Servlet interface Sun company defines two default implementation classes: genericservlet and httpservlet.

Httpservlet refers to a servlet that can handle HTTP requests. It adds some HTTP protocol processing methods to the original servlet interface, which is more powerful than the servlet interface. Therefore, when writing a servlet, developers should usually inherit this class and avoid directly implementing the servlet interface. When implementing the servlet interface, httpservlet overwrites the service method. The code in the method will automatically determine the user's request method. If it is a get request, call the doget method of httpservlet; if it is a post request, call the dopost method. Therefore, when writing servlets, developers usually only need to override doget or dopost methods, not service methods.

4.2. Create and write servlets through eclipse

Check GaCl servlet. Right click the study package → new → servlet, as shown in the following figure:

In this way, we will help us create a servlet named servletdemo1 through eclipse. The created servletdemo01 will have the following code:

This code is automatically generated by eclipse, and the web There are also two pairs of tags in the XML file, < servlet > < / servlet > and < servlet mapping > < / servlet mapping >, which configure servletdemo1, as shown in the following figure:

Then we can access servletdemo1 through the browser, as shown in the following figure:

5、 Servlet development details

5.1. Servlet access URL mapping configuration

Because the client accesses the resources in the web server through the URL address, if the servlet program wants to be accessed by the outside world, it must map the servlet program to a URL address, which works on the web This is done using the < servlet > element and the < servlet mapping > element in the XML file. The < servlet > element is used to register a servlet. It contains two main sub elements: < servlet name > and < servlet class >, which are used to set the registration name of the servlet and the complete class name of the servlet respectively. A < servlet mapping > element is used to map an external access path of a registered servlet. It contains two sub elements: < servlet name > and < URL pattern >, which are used to specify the registration name of the servlet and the external access path of the servlet respectively. For example:

Through the above configuration, when we want to access the servlet named servletdemo1, we can use the following addresses:

   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. Servlet access URL uses * wildcard mapping

The * wildcard can also be used in the URL to which the servlet is mapped, but there can only be two fixed formats: one format is "*. Extension", and the other format starts with a forward slash (/) and ends with "/ *". For example:

* you can match any character, so you can use any URL to access servletdemo1, as shown in the following figure:

For some mapping relationships as follows: servlet1 maps to / ABC / * servlet2 maps to / * servlet3 maps to / ABC servlet4 maps to * Do question: when the request URL is "/ ABC / a.html", "/ ABC / *" and "/ *" match, which servlet responds that the servlet engine will call servlet1. When the request URL is "/ ABC", both "/ ABC / *" and "/ ABC" match. Which servlet responds to the servlet engine and will call servlet3. When the request URL is "/ ABC / A.do", both "/ ABC / *" and "*. Do" match. Which servlet responds to the servlet engine and will call servlet1. When the request URL is "/ A.do", the "/ *" and "*. Do" match, which servlet responds, and the servlet engine will call servlet2. When the request URL is "/ xxx / YYY / A.do", both "/ *" and "*. Do" match. Which servlet responds to the servlet engine and will call servlet2. The principle of matching is "find whoever looks more like"

5.3 differences between servlets and ordinary Java classes

Servlet is a java program that can be used by other Java programs (servlet engine) the Java class called. It cannot run independently. Its operation is completely controlled and scheduled by the servlet engine. For multiple servlet requests from the client, usually, the server will only create one servlet instance object, that is, once the servlet instance object is created, it will reside in memory to serve other subsequent requests until the web The servlet instance object will not be destroyed until the container exits. In the whole life cycle of the servlet, the init method of the servlet is called only once. Each access request to a servlet causes the servlet engine to call the service method of the servlet 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 service () method of the servlet it calls, and the service method will call the doxxx method respectively according to the request method.

If a < load on startup > element is configured in the < servlet > element, the web application will load and create the servlet instance object and call the init () method of the servlet instance object when it starts. give an example:

Purpose: write an initservlet for the web application. This servlet is configured to load at startup and create necessary database tables and data for the whole web application.

5.4. Default Servlet

If the mapping path of a servlet is only a forward slash (/), then this servlet becomes the default servlet of the current web application. For URLs that cannot find a matching < servlet mapping > element in the web.xml file, their access requests will be handled by the default servlet, that is, the default servlet is used to handle access requests that are not handled by other servlets. For example:

When accessing a non-existent servlet, the configured default servlet is used for processing, as shown in the following figure:

In < Tomcat installation directory > \ conf \ web In the XML file, a file named org. XML is registered apache. catalina. servlets. The servlet of defaultservlet and set this servlet as the default servlet.

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

5.5. Thread safety of Servlet

When multiple clients access the same servlet concurrently, the web server will create a thread for each client's access request and call the service method of the servlet in this thread. Therefore, if the same resource is accessed in the service method, it may cause thread safety problems. For example, the following code:

Code without thread safety issues:

Code with thread safety issues:

Define I as a global variable. When multiple threads access variable I concurrently, there will be a thread safety problem, as shown in the figure below: open two browsers at the same time 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.

The thread safety problem only exists when multiple threads operate the same resource concurrently. Therefore, when writing a servlet, if a resource (variable, collection, etc.) is accessed concurrently, there will be a thread safety problem. How to solve this problem?

First look at the following code:

Now this method is to add a lock to the servlet object to ensure that only one thread is accessing the resources in the servlet object at any time, so there is no thread safety problem, as shown in the following figure:

Although this approach solves the thread safety problem, but writing servlets can never deal with thread safety problems in this way. If 9999 people access the servlet at the same time, then 9999 people must queue up in turn.

Sun provides a solution to the thread safety problem of servlets: let servlets implement a singlethreadmodel interface. If a servlet implements a singlethreadmodel interface, the servlet engine will call its service method in single thread mode. Looking at the servlet API, you can see that the singlethreadmodel interface does not define any methods and constants. In Java, the interface that does not define any methods and constants is called the tag interface. One of the most typical tag interfaces you often see is "serializable". This interface also does not define any methods and constants. What is the use of the tag interface in Java? The main function is to mark an object and tell the JVM what the object can do. For example, objects of classes that implement 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 like people in real life, Cloning is not allowed, but as long as the "clonable" interface is implemented, the object can be cloned.

Let the servlet implement the singlethreadmodel interface. Just add the declaration to implement the singlethreadmodel interface in the definition of the servlet class. For a servlet that implements the singlethreadmodel interface, the servlet engine still supports multi-threaded concurrent access to the servlet. The way it uses is to generate multiple servlet instance objects, and each concurrent thread calls an independent servlet instance object. The implementation of singlethreadmodel interface can not really solve the thread safety problem of servlet, because the servlet engine will create multiple servlet instance objects. In the real sense, solving the thread safety problem refers to the problem that a servlet instance object is called by multiple threads at the same time. In fact, singlethreadmodel has been marked as deprecated in servlet API 2.4. The above is the whole content of this article. I hope it will be helpful to your study.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>