JSP operation insider

xiaoxiao2021-03-05  24

Author: Zhao Branch from: open systems world

Regular friends ask, what is the difference between JSP and Servlet? What is the connection between the two? In fact, the performance of servlet technology is very early, which is developed for the application of Java server. Everyone knows that applet is a applet, servlet is a server-side applet. However, after Microsoft's ASP technology appears, the output statement of a row of rows when using the servlet, is very awkward, and this is the case for complex layout or display pages. JSP is to meet this need to be developed on servlet technology. It can be seen that there is an intrinsic blood relationship between JSP and Servlet. When learning JSP, if you can seize this connection, you can understand the operational mechanism of JSP and achieve the effect of halving. This article will pass the inside of JSP operation through the analysis of a JSP operation process, and the technical points in some JSPs are set forth from a new perspective.   helloworld.jsp   We take Tomcat 4.1.17 servers as an example to see how the simplest helloWorld.jsp runs. Code List 1: HelloWorld.jsp

HelloWorld.jsp

<%

String message = "Hello World!";

%>

<% = message%>

This file is very simple, only defines a string variable and outputs. Put this file in the Tomcat's WebApps / root / directory, start Tomcat, access http: // localhost: 8080 / helloworld.jsp, the output in the browser is "HelloWorld!"

Let us see what Tomcat has done. Go to Tomcat / Work / Standalone / localhost / _ directory, you can find the following helloworld_jsp.java, this file is the source file generated when Tomcat parsing HelloWorld.jsp:

Code List 2: HelloWorld_Jsp.Java

Package org.apache.jsp;

Import javax.servlet. *;

Import javax.servlet.http. *;

Import javax.servlet.jsp. *;

Import org.apache.jasper.runtime. *;

Public class helloworld_jsp extends httpjspbase {

......

Public void _jspservice (httpservletRequest Request,

Httpservletresponse response) throws java.io.ioException, servletexception

{

JSPFactory _jspxfactory = null;

Javax.servlet.jsp.pageContext pageContext = null;

HttpSession session = null;

ServletContext Application = NULL;

ServletConfig CONFIG = NULL;

Jspwriter out = NULL;

Object Page = THIS;

JSPWriter_Jspx_out = NULL;

Try {

_jspxfactory = jspfactory.getDefaultFactory ();

Response.setContentType ("Text / HTML; Charset = ISO-8859-1); PageContext = _jspxFactory.getPageContext (this, Request, Response, Null, True, 8192, True);

Application = pageContext.getServletContext ();

CONFIG = pageContext.getServletConfig ();

Session = pageContext.getsession ();

OUT = PageContext.getut ();

_Jspx_out = OUT;

String message = "Hello World!";

OUT.PRINT (Message);

} catch (throwable t) {

OUT = _jspx_out;

IF (out! = null && out.getBuffersize ()! = 0)

Out.clearbuffer ();

IF (pageContext! = null) PageContext.HandlepageException (T);

} finally {

IF (_jspxfactory! = null) _jspxfactory.releasePageContext (PageContext);

}

}

}

As can be seen from the above, helloWorld.jsp first parsed to a Java class helloworld_jsp.java, which inherits in the org.apache.jasper.Runtime.httpjspBase base class, HTTPJSPBASE implements the httpservlet interface. It can be seen that JSP first compiled into a servlet before running, which is the key to understanding JSP technology.

We also know that there are several objects in the JSP page, such as PageContext, Application, Config, Page, Session, Out, etc. You may be strange, why you can use these built-in objects directly in the code snippet in the JSP. Observe _JspService () method, in fact, these built-in objects are defined here. Initialize these built-in objects before analyzing the code snippet in the JSP file.

First, call the JSPFactory's getDefaultFactory () method to obtain a reference to a JSPFactory object of the container implementation (refer to Tomcat 4.1.17). JSPFactory is an abstract class defined in the javax.servlet.jsp package, which defines two static methods set / getDefaultFactory (). The SET method is placed by the JSP container (Tomcat). When the page servlet (ie HelloWorld_JSP class) is placed, it can directly call the JSPFactory.getDefaultFactory () method to get the implementation class of this JSP factory. Tomcat is called org.apache.jasper.Runtime.jspFactoryImpl class.

Then, call this JSPFactoryImpl's getPageContext () method, populate a PageContext, and assign the built-in variable PageConext. Other built-in objects are obtained via this pageContext. The specific process see the code above, and details will not be described here. The page servlet's environment is complete, and the page begins to parse the page. The HelloWorld.JSP page only defines a string variable and then outputs it directly. The parsed code is as follows: Code List 3: JSP page analysis code snippet

String message = "Hello World!";

OUT.PRINT (Message);

Customized tag analysis process

In a large web application, JSP custom labels are usually used to encapsulate page display logic. An analysis of the parsing process of the custom label is very helpful to our in-depth understanding of the operational mechanism of customized labels. Below we run as an example with the homepage of Struts-Example apps attached in Struts1.1.

INDEX.JSP containing custom labels

The download address of Struts1.1 is http://jakarta.apache.org/struts/index.html. Put the downloaded package, you can find Struts-Example.war under the WebApps directory. Copy the WAR package to the Tomcat's WebApps directory, Tomcat will automatically install this package. Access the Struts-Example App to HTTP: // localhost: 8080 / Struts-Example in the browser, the home page of the app is displayed (see Figure 1).

Figure 1 Home

Code List 4: INDEX.JSP

<% @ page contenttype = "text / html; charset = uTF-8" Language = "java"%>

<% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%>

<% @ Taglib URI = "/ Web-INF / STRUTS-LOGIC.TLD" prefix = "logic"%>

<bean: message key = "index.title" /> </ title></p> <p><HTML: BASE /></p> <p></ hEAD></p> <p><body bgcolor = "white"></p> <p>......</p> <p></ body></p> <p></ html: html></p> <p>We only analyze as an example only as an example of <bean: message /> tag in index.jsp, how to analyze this custom label into HTML output. The above code omits other display portions of the page. First, look at the source file of the page in the browser above:</p> <p><html lang = "zH"></p> <p><HEAD></p> <p><Title> Mailreader DemonStration Application (Struts 1.0) </ Title></p> <p></ hEAD></p> <p><body bgcolor = "white"> ......</p> <p></ body></p> <p></ html></p> <p>It can be seen that the container has replaced the <bean: message key = "index.title" /> to a string, displayed as the header of the page.</p> <p>Analytical process</p> <p>So, how does the JSP container complete parsing? View Index_jsp.java files after the work directory jakarta-tomcat-4.1.17 / work / standardalone / localhost / struts-example:</p> <p>Code List 5: INDEX_JSP.JAVA</p> <p>Package org.apache.jsp;</p> <p>Import javax.servlet. *;</p> <p>Import javax.servlet.http. *;</p> <p>Import javax.servlet.jsp. *;</p> <p>Import org.apache.jasper.runtime. *;</p> <p>Public class index_jsp extends httpjspbase {</p> <p>FILE: / / Define references to all processor pools for all custom tags</p> <p>Private org.apache.jasper.runtime.taghandlerpool;</p> <p>_jspx_tagpool_bean_message_key;</p> <p>......</p> <p>FILE: // Page Class Construction Method</p> <p>Public index_jsp () {</p> <p>_JSPX_TAGPOOL_BEAN_MESSAGE_KEY =</p> <p>New org.apache.jasper.runtime.taghandlerpool ();</p> <p>......</p> <p>}</p> <p>Public void _jspservice (httpservletRequest Request,</p> <p>Httpservletresponse response</p> <p>Throws java.io.ioException, servletexception {</p> <p>......</p> <p>_jspxfactory = jspfactory.getDefaultFactory ();</p> <p>Response.setContentType ("text / html; charSet = utf-8");</p> <p>PageContext = _jspxfactory.getPageContext (this,</p> <p>Request, Response, NULL, TRUE, 8192, TRUE;</p> <p>Application = pageContext.getServletContext ();</p> <p>CONFIG = pageContext.getServletConfig ();</p> <p>Session = pageContext.getsession ();</p> <p>OUT = PageContext.getut ();</p> <p>_Jspx_out = OUT;</p> <p>......</p> <p>IF (_jspx_meth_html_html_0 (pageContext))</p> <p>Return;</p> <p>......</p> <p>}</p> <p>File: // The page releases all custom labels attributes when processing exit</p> <p>Public void _jspdestroy () {</p> <p>_jspx_tagpool_bean_message_key.release ();</p> <p>......</p> <p>}</p> <p>}</p> <p>The generated index_jsp.java inherits in org.apache. Jasper.Runtime.httpjspbase. Research this document provides us to understand the operational mechanism of custom labels.</p> <p>As can be seen from the above, Tomcat first defines each custom label and instantizes a TagHandlerPool object for each custom tag when parsing a JSP page. The processing method of the page covers the _ jspservice () method of the parent class, _jspservice method first initializes the environment and assigns a built-in object. Since the index.jsp page is wrapped in a <HTML: HTML /> tag package, Tomcat generates a private method for each tab. <HTML: HTML /> Tag method is _jspx_meth_html_html_0 (). The naming specification of this method can also be seen from here, "_jspx_meth tag prefix tag name This tag appears in the JSP page." Other tags are included in the label, so other tags are parsed in the _jspx_meth_html_html_0 () method. For specific code implementations, see Caidi.com http://linux.ccidnet.com Journal Browse 2003 No. 6. In the _jspx_meth_html_html_0 () method, you first get an instance of org.apache.struts.taglib.html.htmltag from the _jspx_tagpool_html_html_locale pool, then set the page context of this Tag instance, due to the HTML: HTML tag is page The top label, so its Parent is NULL. Then parse the contents of the label. The HTML code is directly output. The following mainly look at the <bean: message key = "index.title" /> tag containing <html: html> </ html: html> tag. Analysis of the Bean: Message Tag is similar to HTML: HTML, Tomcat also puts it in a separate method _jspx_meth_bean_message_0 ().</p> <p>Bean: Analysis of Message Tags</p> <p>Code List 7: _jspx_meth_bean_message_0 () method pieces</p> <p>/ / Treatment method for Message custom labels</p> <p>Private boolean _jspx_meth_bean_message_0 (</p> <p>Javax.Servlet.jsp.tagext.tag _jspx_th_html_html_0,</p> <p>Javax.servlet.jsp.pageContext pageContext) throws throwable {</p> <p>Jspwriter out = pageContext.getut ();</p> <p>/ * ---- Bean: Message ---- * /</p> <p>Org.apache.struts.taglib.bean.Messagetag</p> <p>_jspx_th_bean_message_0 =</p> <p>(org.apache.struts.taglib.bean.MessageTag)</p> <p>_jspx_tagpool_bean_message_key.get (</p> <p>Org.apache.struts.taglib.bean.MessageTag.class);</p> <p>_jspx_th_bean_message_0.setpageContext (PageContext);</p> <p>_JSPX_TH_BEAN_MESSAGE_0.SETPARENT (_jspx_th_html_html_0);</p> <p>_jspx_th_bean_message_0.setkey ("index.title");</p> <p>INT _JSPX_EVAL_BEAN_MESSAGE_0 = _jspx_th_bean_message_0.dostarttag ();</p> <p>IF (_jspx_th_bean_message_0.doendtag () == javax.servlet.jsp.tagext.tag.skip_page) Return True;</p> <p>_jspx_tagpool_bean_message_key.reuse (_jspx_th_bean_message_0);</p> <p>Return False;</p> <p>}</p> <p>Similarly, the HTML: Bean also needs to get an instance of a label class from the pool, and then set the environment. Not detailed here. We only focus on the special processing section of the MessageTag custom label class. The development of custom labels is not within the scope of this article. A bean: Message label is defined in Index.jsp, and sets an attribute: <bean: message key = "index.title" />. When Tomcat is parsed, call the key property setting method setKey () of the MessageTag object, and place the property in. Then call MessageTAG's dostartTAG () and doendTag () methods to complete the resolution. If the return value of the DOENDTAG () method is javax.servlet.jsp.tagext.tag. Skip_page, indicating that the resolution is completed, returns true, Tomcat will immediately stop the execution of the remaining page code and return. Otherwise put the instance of the MessageTag back into the pool.</p> <p>Tag class object instance</p> <p>In order to improve the operational efficiency, Tomcat is done to all custom labels, and the poolization work is done by org.apache.jasper. Runtime.taghandlerpool class. There are two main methods in the TagHandlerPool class, the code is as follows:</p> <p>Code List 8: TagHandlerpool.java</p> <p>Public class taghandlerpool {</p> <p>Private static final int max_pool_size = 5;</p> <p>PRIVATE TAG [] Handlers;</p> <p>Public synchronized tag get (class handlerclass) throws jspexception {...}</p> <p>Public synchronized void reuse (tag handler) {...}</p> <p>}</p> <p>TagHandlerPool simply implements the pool of tag classes, where max_pool_size is the initial size of the pool, and Handlers is an array of TAGs, instances of the label class. Get (class handlerclass) gets an instance of a specified tag class. If there is no instance in the pool, a new instance is new. Reuse (Tag Handler) puts the Handler object back in the pool.</p> <p>At this point, we have the operation of JSP in the container. Although the resolution of each JSP container will differ, but the principles are similar. For written JSP applications, we do not need to interfere with the running process in the container, but if you are familiar with the overall running mechanism, you can have a deeper understanding of JSP / servlet technology.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-33034.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="33034" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.040</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'm83i08JUV5Sd0nPxQKZF_2FUmqn42QfFp4z8_2Bd0uM2NfeO60Sh1hHAxMPg6kFAfc_2BaGCQkcOfcm5uHPGS_2FmtPblQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>