(This article is issued in the first phase of Java Emag) 1. Original and status quo:
Regarding the origins of Template and JSP, it is necessary to tell the ancient times of Web development. At that time, people develop web applications with CGI and write HTML tags in a CGI program.
After this, the world began to develop in different directions: Sun offers a servlet solution similar to CGI, but both CGI or servlet faces the same problem: written in the program, writing HTML tags, no matter what is not a wise solution. SUN has launched JSP technology in 1999. In another world, Scriptlet page scripts represented by PHP and ASP began wide application.
However, if so, the problem is not over, the new problem has appeared: the mixture of the business and HTML tags, which not only leads to the chaos of the page structure, but also makes the code itself difficult to maintain.
The MVC model originated from the late 1970s was introduced. The three roles of the MVC: Model - contains all data and behaviors of data and behavior in the UI. View is the display of the model in the UI. Any information change is processed by the third member in the MVC.
In the subsequent application, the first leap in technology appears: the front-end display logic and the back end business logic separation, COM components, or EJB or CORBA are used to handle business logic, ASP, JSP, and PHP are used for front end display. This is the Model 1 phase developed by the web (page controller mode).
However, this development model has many questions:
1. The page must be written to the ScriptleT call component to obtain the necessary data.
2. Process the display logic Scriptlet code and HTML code mixed interleave.
3. Difficulties in debugging. JSP is compiled into a servlet, and the debug information on the page is not enough to locate an error.
All this is because there is no separation view and controller in Model 1. The complete separation view and the controller become a must. This is MODEL 2. It puts problems in Model 1 - Separates the call to the component (business logic), and transplanting this part of the work to the controller. It seems that it seems to be perfect, but wait, the original controller is separated from the page, how to get the data required by the page, who will handle the page display logic? Two means: 1. Continue to use ASP, PHP or JSP mechanism, but because they are running in a web environment, the data they want to display (the result of backend logic generation) needs to be placed in the Request stream through the controller. ; 2. Using new techniques - template technology, using independent template technology, due to the detached web environment, it will bring considerable convenience to development testing. As for the data you want to enter a POJO, it is not a Request object.
Template technology first starts in PHP's world, there have been two heroes of phpLib Template and FastTemplate. Soon the template technology is introduced into the Java Web development world. Currently popular template techniques are: XSTL, Velocity, JdyNamite, TapeStry, etc. In addition, since JSP technology is currently standard, it is a quite system or using JSP to complete the page display logic section. In addition to Sun's JSTL, each third party organization has also launched its own taglib, one representative is struts tablib.
Second, template technology analysis:
Template technology is essentially, it is a placeholder dynamic replacement technology. A complete template technology requires four elements: 0. Template language, 1. Template file containing template language, 2. With dynamic data, 3. Template Engine. The following four elements are discussed below. (In the discussion process, I only list several different characteristics technology, other techniques or similarity will not be repeated) 1. Template language:
Template language includes: variable identification and expression statement. Depending on the control of the expression, it can be divided into strong control template language and weak control template language. According to the template language and HTML compatibility, it can be divided into compatibility template language and non-compatibility template language.
Template language to handle three points:
1. Scalar tag. Many ways to identify variables into HTML. One is to use a label similar to HTML; the other is to use special identifiers such as Velocity or JDynamite; the third is to extend the HTML tag, such as Tapestry. How many ways to use, a more common consideration is the requirements of "what you see".
2. Conditional control. This is a tricky problem. A simple example is a logistics accompaniment system, and the number of items is lower than a certain value. However, for a specific complex display logic, the conditional control seems to be inevitable. When you put similar to
3. Iterations (loop). Displaying a data form on the web is a very basic requirement, using the collection tag will inevitably, but fortunately, it is usually very simple and enough. It is particularly worth mentioning that PHP template technology and JDynamite techniques use HTML annotation tags to achieve it, and maintain the "resulting" characteristics.
Here are some technical comparisons:
Velocity variable definition: Use a marker expression statement: Strong control language: Variable assignment: #set $ this = "velocity" external reference: #include ($ 1) condition control: #if .... #Nd Non-compatible language JDYNAMITE Variable Definition: Use {} Package Expression Statement: Write in Note Format (
The template file refers to a text file that contains a template language.
Template files cause different results due to compatibility of their template language. Template file with HTML compatibility is just a resource file, which has good reuse and maintenance. For example, JDynamite's template files can not only be multiplexed in different projects, but can even be used with Templates files with PHP programs. For example, Velocity's non-compatible template file, because of its fact is a scriptor, reuse and maintainability is greatly reduced.
3. Data objects with dynamic data:
The template file contains static content, then the dynamic data they need is additionally provided. According to the different data, it can be divided into three types:
1. Map: Use Key / Value to locate. This is the most common technology. If Velocity's VelocityContext is included in the Map object.
Example.vm: Hello from $ Name in The $ project project.
Example.java: velocityContext context = new velocityContext (); context.put ("name", "velocity"); context.put ("project", "
Jakarta
");
2. DOM: Directly operate DOM data objects, such as XSLT utilizing XPath technology.
3. POJO: Directly utilize reflection to obtain DTO objects, and use the JavaBean mechanism to obtain data. Tapestry.
4. Template engine:
The work of the template engine is divided into three steps:
1. Template file and confirm that the template language is in line with the specification.
For example, Velocity, determine that #IF has corresponding #END, etc. In the model of XML XSLT, the XML file label is complete. After these work is completed, the template engine typically parsing the template file into a node tree (including the static content node of the template file and the special node defined by the template engine).
2. Take the data object.
This data object is generally implemented by program delivery references. The existing large number of frames are completed under the base layer, and the processing methods are also different, and there are two techniques to promote technology and pull technology. Push technology: Controller calls the SET method to inject dynamic data, the template engine is obtained by the GET method, typical representative: struts; pull technology: The template engine finds the model corresponding to the view according to the configuration information, call the MODEL's GET method to obtain data, typical representative : TapeStry. 3. Merge template file (static content) and data object (dynamic content), and generate final pages.
The merge mechanism is generally as follows, the template engine traverses each node of this node tree, and render this node, encounter a static content node according to normal input, encountering a special node to obtain the corresponding value from the data object, and perform its expression Statement (if any).
The following detailed description:
Velocity Template Template = Velocity.getTemplate ("Test.wm"); context context = new velocityContext (); context.put ("foo", "bar"); context.put ("Customer", New Customer ()); Template.mege (Context, Writer); When the Velocity.getTemplate method is called, the corresponding method of ResourceManger will be called. ResourceManger first views whether the template file is in cache, if you don't get, generate the Resource object and call the Process () method, determine if the template is valid, if it is valid, generate a Node tree in memory. When calling template.merge (), traversing this Node tree and calls each Node render method. For variables and object node in the template, the Execute () method will also be called to get Value from the Context. Note: ResourceManger Under the Runtime / Resource package, Node is more troublesome under the Runtime / Parser / Node package, first introduces the process of the HTTP request. When the httpRequest request arrives. The request is captured by the ApplicationServlet, and the ApplicationServlet is then taken to the corresponding ENGINE via GetEngine, and the corresponding service is obtained through the GetService of the engine, and the service method is called to perform HTTP requests. Each service acquires the PAGE object through the getPage method of the Requestcycle object and set it to the Active Page of the CYCLE object. The service calls the renderResponse method to perform the output. RenderResponse Calling Page GetResponseWriter (OUTPUT) gets the Writer object and passes it to the CYCLE.RenderPage (Writer) method, which calls the renderpage method. Page When executing renderpage, first determine if there is a request for Listener, if there is a handle, then call the baseComponEntTemplateLoader's Process method to load the template file into and form a Component node tree, and perform the render of the node. Each Component object will acquire object properties through an ONGL mechanism. And write this value to the input stream.
For example: insert component protected void renderComponent (IMarkupWriter writer, IRequestCycle cycle) {if (cycle.isRewinding ()) return; Object value = getValue (); if (value == null) return; String insert = null; Format format = getFormat (); If (format == null) {INSERT = value.tostring ();} else {Try {INSERT = Format.Format (value);} catch (exception ex) {throw new applicationRuntimeException (Tapestry.Format " .unable-to-format, value Writer.attribute ("class", styleclass); renderinformalParameters (Writer, cycle);} if (Getraw ()) Writer.printraw (Insert); Else Writer.print (Insert); if (styleClass! = null) Writer.end (); // } getValue is the value attribute of INSERT. Third, JSP technical analysis
1. JSP technology:
JSP, a servlet after a camouflage. Web Server generates a corresponding JSP class for any JSP, open this class, will find that JSP provides a code generation mechanism that puts all Scriptlet in the JSP file. At the same time, PRINTLN is called to output all HTML tags.
Test.jsp: