Template and JSP technology

xiaoxiao2021-03-06  41

(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 COUNT , it is like our original ASP and What is done in PHP, we will have to face the problems encountered by the Scriptlet embedded web page. I believe that you don't think this is a good writing method like me. In fact, not all template technologies use conditions control, many existing applications such as PHP and I have seen an ASP.NET-based app, of course, Java's JDynamite. There is no logic on this page, but the cost of doing this is to hand over the highlighted selection control to the programming code. You must do a choice. Maybe you are also like me to use conditional control in the web page, nor do you want to write HTML tags in your code, but this display logic is inevitable (if you don't want to be copied by your boss), a viable method It is used to use CSS, which CSS style is determined in programming code. In particular, CSS2 technology, its Selector mechanism, can apply according to the HTML type or even ELEMENT's Attributes to Apply different styles.

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: JSP test </ title> </ head> <body> <table width = "226" border = "0" cellspacing = "0" cellpadding = "0"> < Tr> <TD> <font face = "arial" size = "2" color = "# 000066"> <b class = "headlinebold"> The JSP Test file </ b> </ tr> </ td> </ Font> </ table> <body> </ html> test_jsp.java: package org.apache.jsp; import javax.servlet. *; import javax.servlet.http. *; import javax.servlet.jsp. *; import org.apache.jasper.runtime *;. public class Test _jsp extends HttpJspBase {private static java.util.Vector _jspx_includes; public java.util.List getIncludes () {return _jspx_includes;} 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;</p> <p>try {_jspxFactory = JspFactory.getDefaultFactory (); response.setContentType ( "text / html; charset = ISO-8859-1"); pageContext = _jspxFactory.getPageContext (this, request, response, null, true, 8192, true); Application = pageContext (); config = pageContext.getServletconfig (); session = pageContext.getSession (); out = pageContext.getOut (); _jspx_out = out;</p> <p>Out.write ("<html> / r / n"); out.write ("<head> <title> jsp test </ title> </ head> / r / n"); Out.write ("<body" > / r / n "); out.write (" <table width = / "226 /" border = / "0 /" cellspacing = / "0 /" cellpadding = / "0 /"> / r / n ") Out.write ("<tr> <td> <font face = /" arial / "size = /" 2 / "color = /" # 000066 / "> / r / n / t"); Out.write ( <b class = / "headlinebold /"> the jsp test file "); out.write (" </ b> / r / n / t "); Out.write (" </ tr> </ td> < / font> / r / n / t "); Out.write (" </ Table> / R / N "); Out.write (" <body> / r / n "); out.write (" </ HTML> ");} catch (throwable t) {out = _jspx_out; if (out! = null && out.getBuffersize ()! = 0) out.clearbuffer (); if (pageContext! = null) PageContext.handlepageException (} Finally {if (_jspxfactory! = Null) _jspxfactory.releasePageContext (pageContext);}}} 2. Taglib technology:</p> <p>Taglib as auxiliary technology on JSP, its work essentially relying on JSP technology, but also a custom label translated into Java code, but this time and JSP are slightly different, it also has several processes.</p> <p>Let's take a look at it and achieve 2 points of a Tag:</p> <p>1. Provide a set method of the property, which will now be set at the JSP page. Take the JSTL tag as an example C: Out value = "" /, this value is the entry between JSP data to TAG. So there must be a setValue method in TAG, and the specific properties can be called Value. For example setValue (String Data) {this.data = data;}. This "value" name is defined in TLD. What is the name, you can provide a corresponding set method in tag.</p> <p>2. Handle DostartTAG or DOENDTAG. These two methods are Tagsupport provided. Or C: OUT VALUE = "" / Take the case, when the JSP parsing this tag, the DOSTAG event is triggered at "<", ">" triggers the DOENDTAG event. Logical operations are usually performed in DostartTag, and the output is controlled in DOENDTAG. When dealing with TAG:</p> <p>0. Get the corresponding TAG from tagpool.</p> <p>1. Set the page context for the TAG.</p> <p>2. Set its parent tag for this tag, if not NULL.</p> <p>3. Call the setter method to incur a tag attribute value tag, if the tag is not attribute, this step is skipped.</p> <p>4. Call the DostartTAG method and take the return value.</p> <p>5. If the label has a body, determine if the POP content is determined according to the DostartTAG return value. If you want to POP it, then: setBodyContent (), after, DoinitBody (). If the tag does not have a body, this step is skipped.</p> <p>6. Call DOENDTAG () to determine if the remaining portion of the page is skipped.</p> <p>7. Finally, return the TAG class to tagpool.</p> <p>TAG class is:</p> <p>Package my.customtags;</p> <p>Import javax.servlet.jsp.jspwriter;</p> <p>Import javax.servlet.jsp.pageContext;</p> <p>Import javax.servlet.jsp.tageXt.tagsupport;</p> <p>Public Class Hidden Extends tagsupport {</p> <p>String name;</p> <p>Public hidden () {name = "";</p> <p>Public void setname (String name) {this.name = name;}</p> <p>Public void release () {value = null;}</p> <p>Public int dostarttag () {return Eval_body_includ;</p> <p>PUBLIC INT DOENDTAG () THROWS JSptagexception {</p> <p>Try {pageContext.get (). Write (", you are wellcome";</p> <p>Catch (IOException EX) {throw new jsptagexception ("error!");</p> <p>Return Eval_page;</p> <p>}</p> <p>}</p> <p>JSP page:</p> <p><my: hidden name = "testname" /></p> <p>Generated JSP code:</p> <p>My.customtags.hidden _jspx_th_my_hidden_11 = (my.customtags.hidden) _Jspx_tagpool_my_hidden_name.get (my.customtags.hidden.class);</p> <p>_jspx_th_my_hidden_11.setpageContext (PageContext);</p> <p>_jspx_th_my_hidden_11.setparent (null);</p> <p>_jspx_th_my_hidden_11.setname ("testname");</p> <p>INT _JSPX_EVAL_MY_HIDDEN_11 = _jspx_th_my_hidden_11.dostarttag ();</p> <p>IF (_jspx_th_my_hidden_11.doendtag () == javax.servlet.jsp.tagext.tag.skip_page) Return True;</p> <p>_jspx_tagpool_my_hidden_name.reuse (_jspx_th_my_hidden_11);</p> <p>Return False;</p> <p>Taglib technology offers two mechanisms, Body and Non-Body lead to two branches of Taglib: Display Tag and Control Tag, the former embed HTML tags in Java Code, quite with a web component, while the latter is another Template script.</p> <p>Fourth, two technical programs compare:</p> <p>1. Technology learning is difficult</p> <p>Template technology. Using template technology, the first point is to learn template language, especially strong control template languages. So the template language itself is particularly important. The following is compared to several template techniques based on the main base point based on the friendliness, expressiveness, and the three points of reuse.</p> <p>Velocity: Turbine Project (http://jakarta.apache.org/turbine) uses Velocity technology. 1. The friendliness is not enough. Reason: Strong control type, display control code and HTML mixing appear. It is incompatible with HTML and cannot be seen. In the event of a big HTML page, find the corresponding "#end" from a "#IF" is also a very painful thing. 2. Performance. Reason: Strong control language. 3. Recessive is weak. Reason: Template script and page code mix. XSLT Cocoon Project (http://cocoon.apache.org/) uses XML XSLT methods. The 9CBS community is also adopted. 1. Content and display style separation, this XSLT is best. 2. Slow speed. Reason: Use XPath using XSLT, because it is to resolve the DOM tree, when the XML file is large, the speed is very slow. 3. The friendliness is not enough. Reasons: Due to the HTML file, the page structure, display style, and content are not seen at all. The XSL syntax is more difficult to master, because there is no "ready" editing tool, the cost is high. 4. Performance. Reason: Strong control language. 5. Recessive is weak. Reasons: XSL tags and HTML tags are mixed. JDYNAMITE 1. Equivalence is medium. Reason: Weak control language. 2. Friendly is strong. Reason: The effect obtained by the seen. The Ignore Block in the template can display the page effect under editing conditions, and it will not be output in the run. 3. Strong reuse. Reason: Use the HTML tag. TapeStry 1. Friendly moderate. Reason: The entire TapeStry page file is HTML element. However, since Component rewrites the HTML tag, it is displayed correctly and will not be predictable. 2. Performance. Reason: Strong control language. 3. Strong reuse. Reasons: extended the definition of HTML elements.</p> <p>A large number of Taglibs in JSP can make JSP's page structure, more in line with XML format, and can reuse some page elements. But the code after the compilation of Taglib is huge and messy. Tablib is very unflexible, and things that can be completed are limited. The reusability of Tablib code itself is limited by the Tagsupport definition, not very good. In addition, one of my admits is that taglib's writing itself is not a pleasant thing. Fact I personally oppose this development method. 2. Technology use difficulty</p> <p>Template technology: Template technology itself is separated from the web environment, can be developed and tested without starting Web Server, once the error is detailed, the information is easy to locate. Due to the control of the template engine, only display logic will be processed (although it may be complicated)</p> <p>JSP technology: Working In a web environment, development tests must run Web Server. In addition, some Taglib can generate a new label, and the final layout of the page must also be determined in a web environment. When the test, the error message is not clear, especially Taglib, is extremely difficult to position. Since its essence is a procedure, it is easy to write business logic, even database connection code, causing decoupling.</p> <p>3. Summary</p> <p>Template technology is more focused on the display logic of the page, which is effective to help developers separate views and controllers. It is easier in learning, development and testing.</p> <p>JSP</p> <p>The technology itself is an early technology that it does not propose enough way to separate views and controllers. On the contrary, I think it is itself to encourage developers to do not decouple, because</p> <p>JSP</p> <p>This is easy to insert business logic in your code.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-52747.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="52747" 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.041</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 = 'xok9KpoKrxq_2Buhu9Szg5gBLoec3crUfin2Vd0EUPpoeWDqQfHY6ZLapCsV8Q5M02cpPFfN3I5wzNsUrQDAg5NA_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>