Javaweb Foundation--->servlet (reprint)

Source: Internet
Author: User

See this blog today, feel good, take for reference to learn a bit.

What is a Servlet?

A Java Servlet is a program that runs on a Web server or application server, as a middle tier between a request from a Web browser or other HTTP client and a database or application on an HTTP server.

Using Servlets, you can collect user input from a Web page form, render records from a database or other source, and create Web pages dynamically.

Java servlets typically work with programs that use CGI (Common Gateway Interface, Public Gateway interfaces) to achieve similar results. But there are several advantages to cgi,servlet compared to the following:

    • 1, the performance is obviously better.
    • 2. The Servlet executes within the address space of the WEB server. This makes it unnecessary to create a separate process to process each client request.
    • 3. Servlets are platform-independent because they are written in Java.
    • 4. The Java security Manager on the server performs a series of restrictions to protect resources on the server computer. Therefore, the Servlet is trustworthy.
    • 5. The full functionality of the Java class library is available to the Servlet. It can interact with applets, databases, or other software through the sockets and RMI mechanisms.
Second, the life cycle of the servlet

The Servlet life cycle can be defined as the entire process from creation to destruction. The following are the procedures that the Servlet follows:

    • 1. The Servlet initializes by calling the Init () method.
    • 2. The Servlet invokes the service () method to process the client's request.
    • 3. The Servlet terminates (ends) by calling the Destroy () method.
    • 4. Finally, the Servlet is garbage collected by the JVM's garbage collector.

Init () method

The Init method is designed to be called only once. It is called the first time the Servlet is created, and is no longer invoked on subsequent user requests. Therefore, it is used for one-time initialization, just like the Applet's Init method.

The servlet is created when the user first invokes the URL corresponding to the servlet, but you can also specify that the servlet is loaded the first time the server is started.

Service () method

The service () method is the primary way to perform the actual task. The Servlet container (that is, the WEB server) invokes the service () method to process requests from the client (browser) and writes the formatted response back to the client.

Each time the server receives a Servlet request, the server generates a new thread and invokes the service. The service () method checks the HTTP request type (GET, POST, PUT, DELETE, and so on) and calls Doget, DoPost, Doput,dodelete, and so on, when appropriate.

Destroy () method

The Destroy () method is called only once and is called at the end of the Servlet's life cycle. The Destroy () method allows your Servlet to shut down a database connection, stop a background thread, write a Cookie list or hit counter to disk, and perform other similar cleanup activities.

After the Destroy () method is called, the Servlet object is marked as garbage collection.

third, how to understand the servlet single-instance multithreading?

When different users make requests for the same business (such as registration), how many servlet instances are there in the container at this time?

The answer is: There is only one servlet instance . A servlet is loaded into memory and instantiated the first time it is accessed. The same business request shares a servlet instance. Different business requests typically correspond to different servlets.

Because servlet/jsp is executed in multithreaded mode by default, you need to take a very careful look at the security of multithreading when writing code.

Multithreading problems in JSP:
When a client requests a JSP file for the first time, the server compiles the JSP into a class file, creates an instance of the class, and creates a thread to process the client's request. If more than one client requests the JSP file at the same time, the server creates multiple threads. Each client request corresponds to a thread. Multi-threaded execution can greatly reduce the resource requirements of the system, and increase the concurrency and response time of the system. 、

The variables that may be used in the JSP are described below:
instance variable : an instance variable is allocated in the heap and shared by all threads that belong to that instance, so it is not thread-safe.
8 class variables provided by the JSP system
The out,request,response,session,config,page,pageconxt used in JSPs are thread-safe (because the Request,respone objects for each thread are not the same, There is no sharing problem, application is used throughout the system, so it is not thread-safe.

Local Variables : Local variables are allocated on the stack because each thread has its own stack space, so it is thread-safe .
static Classes : Static classes are not instantiated, can be used directly, and are not thread-safe .

External Resources : In a program, there may be multiple threads or processes concurrently manipulating the same resource (for example, multiple threads or processes simultaneously write to a file). You should also pay attention to the synchronization problem at this point.

Servlet single-instance multithreading mechanism:

Servlets use multithreading to handle multiple requests at the same time. The servlet relies on a line pool service request. The thread pool is actually a series of worker thread collections. The servlet uses a dispatch thread to manage worker threads.
When a container receives a servlet request, the dispatch thread selects a worker thread from the thread pool, passes the request to the worker thread, and then executes the servlet's service method by that thread. When this thread is executing, the container receives another request, and the dispatch thread also selects another worker thread from the thread pool to serve the new request. The container does not care whether the request accesses the same servlet. When the container receives multiple requests to the same servlet at the same time, the servlet's service () method executes concurrently on multiple threads.
The servlet container defaults to single-instance multithreading to handle requests, which reduces the overhead of generating servlet instances, increases response time to requests, and can be used by Tomcat in Server.xml <Connector> Element sets the number of threads in the thread pool.

Iv. How to develop a thread-safe servlet

1. Implement Singlethreadmodel interface
  This interface specifies how the system handles calls to the same servlet. If a servlet is specified by this interface, then the service method in this servlet will not have two threads being executed concurrently, and there is no thread-safe issue, of course. This method simply changes the class header definition of the previous concurrent test class to:

public class Concurrent Test extends HttpServlet implements Singlethreadmodel {
............
}
2. Synchronize the operation of the shared data

  Using the synchronized keyword ensures that only one thread can access the protected segment at a time

3. Avoid using instance variables

  The thread safety problem in this example is caused by an instance variable, which is thread-safe as long as the instance variable is not used in any of the methods inside the servlet.  

V. The difference between servlet and JSP 1. The JSP is compiled into a servlet. (The essence of JSP is that SERVLET,JVM can only recognize Java classes, not the code of the JSP, the Web container compiles the JSP code into the Java class that the JVM can recognize)
2. JSP is better at displaying the page, and the servlet is better at logic control.
3. There are no built-in objects in the servlet, and built-in objects must pass the HttpServletRequest object. HttpServletResponse objects as well as HttpServlet objects. JSP is a simplification of servlets, and using JSP requires only the content that the programmer needs to output to the client, how the Java script in the JSP is mosaicked into a class, and is done by the JSP container. The servlet is a complete Java class, and the service method of this class is used to generate a response to the client. 4. For static HTML tags, the servlet must use a page output stream to output rows

Javaweb Foundation--->servlet (reprint)

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.