Running inside of JSP

Source: Internet
Author: User
Tags config key locale reference tag name throwable tld tomcat
JS often have friends ask, JSP and servlet What is the difference between the two and what is the connection? In fact, the advent of the servlet technology is very early, it was developed for Java server-side applications. We all know that applet is the application applet, the servlet is the server-side applet. However, with the advent of Microsoft's ASP technology, the output statements for a row of rows when using a servlet to respond to output appear to be clumsy, especially for complex layouts or display pages. JSP is designed to meet this need on the servlet technology development. Visible, JSP and the servlet has an intrinsic blood relationship, in learning JSP, if you can grasp this connection, you can more profoundly understand the operating mechanism of JSP, to achieve a multiplier effect.

This article will be through the analysis of a JSP running process, in-depth JSP running insider, and from a new perspective on some of the technical points in JSP.

helloworld.jsp

Let's take the Tomcat 4.1.17 server for example to see how the simplest helloworld.jsp works.

Code Listings 1:helloworld.jsp

helloworld.jsp
<%
String message = "Hello world!";
%>
<%=message%>



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

Let's see what Tomcat has done. Go to Tomcat's workstandalonelocalhost\_ directory to find the following Helloworld_jsp.java, which is the source file generated when Tomcat resolves helloworld.jsp:

Code Listings 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.getout ();
_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 you can see from the above, helloworld.jsp is first parsed into a Java class at runtime Helloworld_ Jsp.java, the class inherits from the Org.apache.jasper.runtime.HttpJspBase base class, and Httpjspbase implements the HttpServlet interface. It is visible that the JSP is first compiled into a servlet before running, which is the key to understanding JSP technology.

We also know that there are several objects built into the JSP page, such as PageContext, Application, config, page, session, out, and so on, you might wonder why you can use these built-in objects directly in code snippets in your JSP. Observe the _jspservice () method, which is actually defined here in a few built-in objects. These built-in objects are initialized before the code fragment in the JSP file is parsed.

First, the Jspfactory getdefaultfactory () method is invoked to obtain a reference to a Jspfactory object of the container implementation (the Tomcat 4.1.17 in this article). Jspfactory is an abstract class defined in the javax.servlet.jsp package that defines two static method Set/getdefaultfactory (). The set method is placed when the page servlet (that is, the Helloworld_jsp Class) is instantiated by the JSP container (TOMCAT), so you can call the Jspfactory.getdefaultfactory () method directly to get the implementation class for this JSP factory. Tomcat is calling the Org.apache.jasper.runtime.JspFactoryImpl class.

Then, call this Jspfactoryimpl Getpagecontext () method, populate a PageContext return, and assign to the built-in variable pageconext. Other built-in objects are obtained through the PageContext. The specific process see the code above, no longer repeat here. The page Servlet's environment is set up to begin parsing the page. The helloworld.jsp page simply defines a string variable and then outputs it directly. The parsed code is as follows:

Code listings 3:jsp Code Snippets after page parsing

String message = "Hello world!";
Out.print (message);



The parsing process for custom labels

In a medium and large Web application, JSP custom tags are typically used to encapsulate the page display logic. Analyzing the container's parsing process for the custom label is very helpful for us to understand the operation mechanism of the custom label in depth. Here's how to run the home page of the Struts-example application included with Struts1.1b.

index.jsp that contain custom labels

Struts1.1b's download address is http://jakarta.apache.org/struts/index.html. Unzip the downloaded package and find Struts-example.war in the WebApps directory. Copy the war package to Tomcat's WebApps directory, and Tomcat installs the application package automatically. The http://localhost:8080/struts-example access to the Struts-example application in the browser will display the application's home page (see Figure 1).



Figure One application's homepage

Code Listings 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"%>
<title><bean:message key= "Index.title"/></title>
<body bgcolor= "White" >
......
</body>



We only analyze the <bean:message/> tags in index.jsp to see how the container resolves the custom label to HTML output. The above code omits other display parts of the page. First, look at the source file for the page in the browser above:

<title>mailreader Demonstration Application (Struts 1.0) </title>
<body bgcolor= "White" >
......
</body>



As you can see, the container has replaced the <bean:message key= "Index.title"/> with a string that appears as the title of the page.

Parsing process

So, how does the JSP container finish parsing? View the parsed Index_jsp.java file under the working directory Jakarta-tomcat-4.1.17workstandalonelocalhoststruts-example:

Code Listings 5:index_jsp.java

Package org.apache.jsp;

Import javax.servlet.*;
Import javax.servlet.http.*;
Import javax.servlet.jsp.*;
Import org.apache.jasper.runtime.*;
public class Index_jsp extends Httpjspbase {
Define a reference to the processor pool class for all custom tags
Private Org.apache.jasper.runtime.TagHandlerPool;
_jspx_tagpool_bean_message_key;
......
How to construct a page class
Public index_jsp () {
_jspx_tagpool_bean_message_key =
New Org.apache.jasper.runtime.TagHandlerPool ();
......
}

public void _jspservice (HttpServletRequest request,
HttpServletResponse response)
Throws Java.io.IOException, Servletexception {
......
_jspxfactory = Jspfactory.getdefaultfactory ();
Response.setcontenttype ("Text/html;charset=utf-8");
PageContext = _jspxfactory.getpagecontext (This,
Request, Response,null, True, 8192, true);
application = Pagecontext.getservletcontext ();
Config = Pagecontext.getservletconfig ();
Session = Pagecontext.getsession ();
out = Pagecontext.getout ();
_jspx_out = out;
......
if (_jspx_meth_html_html_0 (PageContext))
Return
......
}
The page releases the properties of all custom tags when processing exits
public void _jspdestroy () {
_jspx_tagpool_bean_message_key.release ();
......
}
}



The generated Index_jsp.java inherits from Org.apache. Jasper.runtime.HttpJspBase. Studying this document provides a way for us to understand the operating mechanism of custom tags.

As you can see from the above, when Tomcat parses a JSP page, it first defines and instantiates a Taghandlerpool object for each custom tag. The processing method of the page overrides the _ Jspservice () method of the parent class, and the _jspservice method initializes the environment first, assigning values to the built-in objects. Since the index.jsp page is packaged by a
In the _jspx_meth_html_html_0 () method, first from the _jspx_tagpool_html_html_ Locale pool to get a Org.apache.struts.taglib.html.HtmlTag instance, and then set the tag instance of the page context and the parent tag, because the html:html tag is the top level of the page tag, So its parent is null. The contents of the label are then parsed. HTML code output directly, the following mainly look at
Analysis of Bean:message label

Code Listing 7:_jspx_meth_bean_message_0 () method fragment

Processing method of custom label for message
Private Boolean _jspx_meth_bean_message_0 (
Javax.servlet.jsp.tagext.Tag _jspx_th_html_html_0,
Javax.servlet.jsp.PageContext PageContext) throws Throwable {
JspWriter out = Pagecontext.getout ();
* *----bean:message----* *
Org.apache.struts.taglib.bean.MessageTag
_jspx_th_bean_message_0 =
(ORG.APACHE.STRUTS.TAGLIB.BEAN.MESSAGETAG)
_jspx_tagpool_bean_message_key.get (
Org.apache.struts.taglib.bean.MessageTag.class);
_jspx_th_bean_message_0.setpagecontext (PageContext);
_jspx_th_bean_message_0.setparent (_JSPX_TH_HTML_HTML_0);
_jspx_th_bean_message_0.setkey ("Index.title");
int _jspx_eval_bean_message_0 = _jspx_th_bean_message_0.dostarttag ();
if (_jspx_th_bean_message_0.doendtag () = = Javax.servlet.jsp.tagext.Tag.SKIP_PAGE)
return true;
_jspx_tagpool_bean_message_key.reuse (_JSPX_TH_BEAN_MESSAGE_0);
return false;
}



Also, for Html:bean, you need to get an instance of the tag class from the pool, and then set the environment. Don't repeat it here. We only focus on the special processing part of the Messagetag custom label class. The development of custom label classes is not covered in this article. A bean:message tag is defined in index.jsp and a property is set: <bean:message key= "Index.title"/>. When Tomcat resolves, it invokes the Key property setting Method Setkey () of the Messagetag object, placing the property in. The Messagetag doStartTag () and Doendtag () methods are then invoked to complete the parsing. If the return value of the Doendtag () method is Javax.servlet.jsp.tagext.Tag. Skip_page, indicating that parsing has been completed, returning True,tomcat will immediately stop the execution of the remaining page code and return. Otherwise put the Messagetag instance back into the pool.

Pooling of Label class object instances

To improve operational efficiency, Tomcat pooled all the custom label classes and pooled the work by Org.apache.jasper. Runtime. Taghandlerpool class complete. The Taghandlerpool class has two main methods, the code is as follows:

Code Listings 8:taghandlerpool.java

public class Taghandlerpool {
private static final int max_pool_size = 5;
Private tag[] handlers;
Public synchronized Tag get (Class handlerclass) throws Jspexception {...}
Public synchronized void reuse (Tag handler) {...}
}



Taghandlerpool simply realizes the pooling of the label class, where Max_pool_size is the initial size of the pool, handlers is an array of tag, storing instances of the tag class. Get (class Handlerclass) Gets an instance of the specified label class, and if there are no instances available in the pool, the new instantiation is one. Reuse (Tag handler) puts the handler object back in the pool.

At this point, we already have a clear understanding of how the JSP is running in the container. Although the parsing results for each JSP container are different, the principles are identical. For writing JSP applications, we do not need to interfere with the operation of the container, but if you are familiar with the entire underlying operating mechanism, you can have a deeper understanding of jsp/servlet technology.



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.