javaweb--in-depth servlet and JSP (operating principle)

Source: Internet
Author: User
Tags event listener

javaweb--in-depth servlet and JSP (operating principle)Review Review!!! Get Up!! Servlets and JSPs are the most basic members of the Java EE specification, and they are a key knowledge of Java Web Development, even though we often use frameworks to develop the backend, but we still need to understand their principles. The structure of the article: (1) parsing the servlet, (2) parsing the JSP; I. Profiling the servlet: (1) Overview: servlet is a server-side Java application independent of platform and Protocol, which can generate dynamic Web pages. It serves as a middle tier for web browsers or other HTTP clients to make requests, interact with databases or applications on the HTTP server. A servlet is a server-side program written in Java that is independent of protocol and platform. The servlet runs in the Java server. Java Servlets can dynamically scale the capabilities of the server and provide Web services in a request-response pattern. Servlets are Java programs that use Java Servlet applications to design interfaces and related classes and methods. It runs on the Web server or on the application server and expands the server's capabilities. The servlet loads the Web server and executes it within the Web server. A servlet is a server-side application component based on Java technology, and a servlet client can make a request and get a response to that request, which can be any Java program, browser, or any device. (2) Basic knowledge: 1. Configuration: The edited servlet source file does not respond to user requests, it must be compiled into a class file, the compiled class file is placed under the web-inf/classes path, if the servlet has a package, You also need to place the class file under the package path. 2. Life cycle:

The JSP page that is written will eventually be compiled by the Web container into the corresponding servlet, and when the servlet is running in the container, the creation and destruction of its instances are not determined by the program ape, but by the Web container. The servlet container is responsible for loading and instantiating the servlet, depending on the setting when the container starts (loadonstartup greater than or equal to 0 is initialized at container startup, the smaller the priority is higher), or deferred initialization until the first request; Initialize: Init (), perform some one-time actions, servletconfig configuration objects, get initialization parameters, Access ServletContext context Request Processing: servlet container encapsulates request and response object to the service method of the corresponding servlet, for HttpServlet, is HttpServletRequest and httpservletresponse; Using the template method pattern in HttpServlet, the service method is further dispatched to the Doget,dopost and other methods according to the HTTP request method for processing For HTTP request processing, only the corresponding HTTP Servlet method (Doget) that supports the HTTP method can be overridden, or it is put back to 405 (Method not allowed). 3. Accessing the configuration parameters of the servlet: When configuring a servlet, additional configuration parameters can be added, and by using configuration parameters, it is possible to provide better portability and avoid coding the parameters in the program code. There are two ways to configure parameters: (1) specified by @webservlet's InitParams property. (2) The number of 4.Servlet through the Web. xml file: The servlet is thread insecure by default, and only one instance of each servlet in a container. Standardwrapper source code, this class is responsible for the creation of the servlet, where the number of instances created in Singlethreadmodule mode can not exceed 20, that is, can only support 20 threads to access this serlvet, therefore, This object pool is designed to further limit concurrency and scalability. 5. Disadvantages: Low development efficiency, poor program portability, poor program maintainability 6. servlet in the standard MVC pattern: Only as a controller, the Java EE application architecture follows the MVC pattern, in which JSP acts as a presentation layer technology and has two points: 1. Responsible for collecting user request parameters; 2 . Renders the application's processing results, status, and data to the user. 7. Thread Insecurity in  :servletThe default thread is unsafe, single-threaded, so for the shared data (static variables, object instances in the heap, etc.) to maintain synchronization control, do not use the service method or doget, such as the service assigned by the method, directly using the Synchronized method, It is obviously necessary to control the size of the synchronization control block of the business control, the time-consuming operation that does not affect thread safety is moved out of the synchronization control block; a thread pool is supported behind the servlet multithreading mechanism, and the thread pool creates a certain number of thread objects at the beginning of initialization, by increasing the utilization of these objects. Avoid creating objects at high frequencies to achieve the goal of improving program efficiency. (A servlet's service method is executed by a thread, and the servlet is in a singleton pattern in Tomcat, and the servlet's thread-safety problem is only apparent when there is a lot of concurrent access and is difficult to find, so pay special attention when writing a servlet program.) Thread-safety issues are primarily caused by instance variables, so you should avoid using instance variables in Servlets. If the application design cannot avoid using instance variables, use synchronization to protect the instance variables to be used, but to ensure the best performance of the system, you should synchronize the code path with the least available availability. 8. Asynchronous processing: Waiting in a servlet is an inefficient operation because it is a blocking operation. The ability to handle requests asynchronously enables a thread to return to the container to perform more tasks. When the request is started asynchronously, another thread or callback can either: (1) Generate a response, or (2) request dispatch, or (3) call completion; Key method: Enable: Allow servlet to support asynchronous support: Asyncsupported=true ; start Asynccontextasynccontext=req.startasynccontext (); Startasynccontext (REQ,RESP); completion: Asynccontext.complete (); The dispatch must be called before the Startasync call, and the same asynccontext cannot invoke both dispatch and complete dispatch: Asynccontext.dispatch ();d Ispatch ( Stringpath);d Ispatch (Servletcontextcontext,stringpath); cannot be called after complete, it is illegal to dispatch from a synchronous servlet to an asynchronous servlet; timeout: asynccontext.settimeout (Millis); After a timeout, the operation cannot be done through Asynccontext, but other time-consuming operations can be performed;After the step cycle begins, the container-initiated dispatch has returned, calling the method to throw illegalstateexception; If set to 0 or less than 0 means notimeout; time-out indicates that the HTTP connection is over, HTTP is closed, and the request is over. Start a new thread: through the Asynccontext.start (Runnable) method, submit a task to the thread pool, where you can use Asynccontext (before timeout); Event listener: AddListener (newasynclistener{... }); OnComplete: Callback at completion, and if dispatched, the OnComplete method is deferred until the dispatch returns the container for the call ; OnError: You can get an exception by asyncevent.getthrowable; OnTimeOut: Time-out callback; Onstartasync: When a new asynchronous period (called Asynccontext) is started in the Startasynccontext, the Callback, timeout and exception handling, step: (1) Call ontimeout/onerror of all registered Asynclistener instances, (2) If there is no Asynclistener call Asynccontext.complete () or Asynccontext.dispatch (), execute a status code of HttpServletResponse. Sc_internal_server_error error Dispatch; (3) If the error page is not found or the error page does not call Asynccontext.complete ()/dispatch (), the container calls the complete method Servlet life terminates: When a servlet container determines that a servlet is removed from the service, it can release any resources and persisted state that the servlet occupies, and so on, by calling the Destroy () method. Before calling the Destroy method, you must ensure that all threads executing the service method are executing or timed out, and that the servlet instance can be garbage collected, of course, when the collection is not deterministic, so the destroy method is necessary. (3) Operating principle: When the Web server receives an HTTP request, it will first determine the content of the request-if it is a static web page data, the Web server will process itself, and then generate response information, if dynamic data is involved, the Web server will forward the request to the servlet container. At this point the servlet container will find the corresponding servlet instance that handles the request and the result will be sent back to the Web server and returned to the client by the Web server. NeedleThe same Servlet,servlet container establishes a servlet instance the first time an HTTP request is received, and then initiates a thread. The second time an HTTP request is received, the servlet container does not need to establish the same servlet instance, but instead initiates a second thread to service the client request. So multithreading can not only improve the efficiency of web application execution, but also reduce the burden of Web server system. Rudely explained the request to the container process

Explains the request-to-container-to-servlet cycle process

Text commentary: 1. The client makes a request->web the server forwards to the Web container tomcat;2. The Tomcat main thread responds to a request that is forwarded to the user to create two objects: HttpServletRequest and HttpServletResponse 3. Find the correct servlet,tomcat from the URL in the request to create or assign a thread to it, and pass the two objects created in step 2 to the thread; 4.Tomcat calls the servlet's Servic () method, depending on the request parameter call Doget () or Dopost () method; 5. Assuming an HTTP GET request, the Doget () method generates a static page and combines it into the response object; When the servlet thread ends: Tomcat sends the Response object to the HTTP response back to the client, while deleting the request and response objects. You can understand the life cycle of the servlet: The Servlet class is loaded (corresponding to 3 steps), the servlet is instantiated (3 steps), the Init method is called (corresponding to 3 steps), the service () method is called (corresponding to 4, 5 steps), and the Destroy () method is called (corresponding to 6 steps). Note: 1. Time to create a Servlet object: When the servlet container starts: reads the information from the Web. XML configuration file, constructs the specified Servlet object, creates a ServletConfig object, and invokes the ServletConfig object as a parameter to invoke the in of the Servlet object It approach. After the servlet container is started: The client makes a request to the servlet for the first time, the servlet container determines if there is a specified Servlet object in memory, creates it if not, and then creates a HttpRequest, HttpResponse object based on the client's request. This invokes the service method of the Servlet object. The servlet servlet container automatically creates the servlet at startup, which is determined by the properties set for the servlet in the Web. xml file. From there, we can see that the same type of servlet object exists as a singleton in the servlet container. 2. In the servlet interface and Genericservlet, there are no doget (), DoPost (), and so on, these methods are defined in HttpServlet, but all return error information, so each time we define a servlet , you must implement these methods such as Doget or Dopost. The httpservlet that we often use are inherited from Genericservlet implementations. Ii. anatomy JSP (1) Overview: JSP and ServletIs the same, because the JSP eventually needs to be compiled into a servlet to run, in other words, the JSP is a draft file that generates Servler. JSP is the embedding of Java code in HTML, or the use of JSP tags, including the use of user-defined tags, so that content can be dynamically provided. Early morning JSP application is more extensive, a Web application can be all composed of JSP pages, only need a small amount of javabean can, but this led to the JSP responsibility is too complex, this is the Java EE Standard appearance is undoubtedly timely, so JSP slowly developed into a single performance technology, The responsibility for the business logic components and the persistence layer components is no longer assumed. Principle Overview: (a brief explanation) the nature of the JSP is the servlet, which uses the output stream to dynamically generate an HTML page when the user specifies that the servlet sends the request. Because it contains a large number of HTML tags. The format of static text causes the servlet to be very inefficient in its development, and all the performance logic, including layout, color, and image, must be coupled in Java code, where static parts do not require Java program control. Only those page content that needs to be read from the database or dynamically generated will be controlled using Java scripting. Therefore, the JSP page content has the following two parts: static part: HTML tag Dynamic part: Java Script (2) Basic knowledge: The instruction is omitted, the random check has a bunch. Focus on its built-in objects: First, we can go to a directory on our own to see the JSP compiled into the servlet code. The directory is: your eclipse's working directory: for example: E:\eclipse\workplace.metadata.plugins\org.eclipse.wst.server.core\tmp0\work\ from, We can see there are nine hidden objects, some of them final, some not. 1.request (most used): An object of HttpServletRequest (which may be used on JSP pages). The request scope is only for server-side jumps. Used to receive request information sent by the client. Note: A single parameter can be received using GetParameter (), and a set of parameters will be received with Getparametervalues (). Be careful, however, that if GetParameter and getparametervalues receive parameters, the returned content is null, which can produce nullpointerexception, so it is a good idea to determine whether the received parameter is NULL. To get the name of the header information, use the Getheadernames () method of the request and use the GetHeader () method to remove the contents of each header message. For example: Language, host, CooKie and so on. An object of 2.response:httpservletresponse (almost no method in the JSP page that calls Response) is the primary function of responding to a client's request and sending the results of the Web server's processing back to the client. Set HEADER information: The client and server side often need to send a lot of extra information. The server side can use the SetHeader method to set the header information to refresh and specify the refresh time, as well as the path URL of the jump. Such as: examples are those pages often prompt "3 seconds after the jump to the first page" operation. If the timer is 0, the jump is unconditional. Note: Timed jumps belong to the client jump. And this set the way to jump head information, simple HTML can also be done, so to the actual consideration, To request a dynamic page, the JSP is required to write 3.pageContext: the context of the page, representing the current page, is a PageContext object, you can get from the object to the other 8 hidden objects, you can also get to the current page of other information. (Use it when learning custom tags, rarely used directly on JSP pages, 1 ' but important). The scope is scoped to the current page only. In fact, PageContext can set any range of properties, while other operations are re-wrapping this functionality. However, it is generally customary to use the PageContext object to set properties that are saved in a page range. He is rarely used to set properties for other scopes. 4.session: A session on behalf of the browser and server, is an object of HttpSession, followed by detailed learning. After this session property is set, it can be obtained in any page related to the Settings page. That is, both the client jump and the server-side jump can get properties. However, if you open a new browser to access the JSP page, you cannot get the session property. Because each new browser connects to the server, it is a new session. 5.application: Represents the current web app. is a ServletContext object. The properties of this setting are visible to all users (sessions). Such properties are saved on the server. 6.config: The ServletConfig object of the servlet corresponding to the former JSP (almost unused at development time). If you need to access the initialization parameters of the current JSP configuration, you need to pass the mapped address. Map JSP Mode:

7.out: function: Completes the output operation of the page. In development, however, the output is typically done using an expression. The JspWriter object, often called OUT.PRINTLN (), can print the string directly to the browser. 8.page refers to the Servlet object corresponding to the current JSP, but to the object type, only the method of the object class is called (hardly used). is the current JSP object. 9.exception: can only be used if the iserrorpage= "true" of the page directive is declared. <%@ page iserrorpage= "true"%> approximate usage frequency: pagecontext,request,session,application; (The range of the scope of the property is small to large) out,response, Config,page,exception (3) JSP operating principle:


1. When a Web container (servlet engine) receives a request for access to a URL with a. jsp extension, the container will hand over the access request to the JSP engine to process 2. Each JSP page is first accessed, the JSP engine translates it into a servlet source program, and then compiles the servlet source program into serv Let. class file and then loaded and interpreted by the Web container (servlet engine) like a normal servlet program to execute the servlet program translated by the JSP page and execute the Jspinit () method of the Servlet instance ( The Jspinit () method is executed only once in the lifetime of the servlet): 3. Then create and start a new thread, and the new thread invokes the instance's Jspservice () method. (For each request, the JSP engine creates a new thread to process the request.) If more than one client requests the JSP file at the same time, the JSP engine creates multiple threads, one for each client request. 4. When the browser invokes a JSP file, the servlet container encapsulates the browser's request and response to the browser as HttpServletRequest and HttpServletResponse objects. Also call the Jspservice () method in the corresponding servlet instance to pass the two objects as parameters to the Jspservice () method. After the 5.jspService () method executes, the HTML content is returned to the client. If the JSP file is modified, the server will decide whether to recompile the file based on the settings. If recompilation is required, replace the compiled result with the in-memory servlet and continue with the above process. If at any time due to insufficient system resources, the JSP engine will somehow remove the servlet from memory in an indeterminate manner. When this happens, the Jspdestroy () method is called first, and then the servlet instance is tagged for "garbage collection" processing. Supplement: 1. The JSP specification does not explicitly require that the script code in the JSP must be in the Java language, and that the script code in the JSP can be written in a scripting language other than the Java language, but the JSP page must eventually be converted into a javaservlet program. 2. You can pre-compile all of the JSP pages in a servlet program before the Web application is officially published. 3. Multithreaded execution can greatly reduce the resource requirements of the system, increase the concurrency and response time of the system, but should pay attention to the multi-threading programming constraints, because the servlet is always resident in memory, so the response is very fast. 4. Although JSP is highly efficient, there are some minor requirements for conversion and compilation at the first callThe delay. Some initialization work can be done in jspinit (), such as establishing a connection to a database, establishing a network connection, getting some parameters from a configuration file, and releasing the appropriate resources in Jspdestory (). Reference blog: http://blog.csdn.net/fengdongkun/article/details/8159381http://www.cnblogs.com/mlloc-clove/p/3549777. HTML is good, javaweb– into the servlet and JSP (operating principle) is finished. This blog is my review phase of some notes, to share experience to everyone. Welcome to point out the error below, learn together!! Your point of praise is the best support for me!! Reprinted: Jackfrost's Blog

javaweb--in-depth servlet and JSP (operating principle)

Related Article

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.