Develop web applications using JSP 2.0

xiaoxiao2021-03-06  111

Develop web applications using JSP 2.0

Author: Qusay H. Mahmoud July 2003

JSP (JavaServer Pages) technology is a further abstraction of Servlet, which is developed by Java Community Process, which is an open-ended, free acquisition specification, which is also a J2EE (Java 2 Enterprise Edition). An important part of. Many commercial application servers are supported by BEA WebLogic, IBM WebSphere, Live Jrun, and Orion support JSP technology.

From the ticket reservation system, banking system to the shopping system, the Web is applied to the application JSP technology. The new release version 2.0 is an upgrade to JSP1.2, which has added some interesting new features. The goal of JSP2 is to make dynamic web pages easier and do not need to learn Java programming languages.

This article includes:

Provides a tutorial with rich sample code to make you familiar with JSP2.0's new feature of JSP2.0 provides some sample code to use JSP2.0 development applications, and you can use this code to be slightly modified for you. s application.

If you are not familiar with JSP, you are a good idea from JSP2.0. But if you want to learn JSP1.2, maybe you need to learn from the JSP tutorial.

JSP 2.0

JSP 2.0 is an upgrade to JSP 1.2, increasing a few interesting new features that make it easier for web application designers and developers. The goal of JSP 2.0 is more easier to use than before, but more importantly, it is necessary to use it without learning the Java language itself. It adds a new extension mechanism called SimpleTAG to simplify the label API (TAG API).

In addition to some other improvements, the most important new features introduced by JSP 2.0 include:

A simple expression language (EL) can be used to easily access data from the JSP page, which simplifies the writing of JSP-free-free applications, do not need Java Scriptlet or Java expression For direct use of JSP technology to define reusable custom behaviors, this syntax uses .tag and .tagx files, such files can be written by developers or web authors; 3XML syntax has been substantially improved, increased A new standard file extension (.tagx is used for label files, .jspx is used for JSP files).

This article mainly discusses expression language, simplified label API and label files. I believe that the current JSP developers will find that these important features are not only interesting, but also very useful.

Why is it from 1.2 to 2.0?

The version number in the Java Specification (JSR 152) is initially set to 1.3. But as you will see later, since these new features have such a profound impact on the development model of JSP applications, the expert group is necessary to upgrade the primary version number to 2.0, so that this effect can be fully reflected. In addition, the new version number also helps to attract the attention of developers to these interesting new features. It is gratifying that all legitimate JSP1.2 pages is also a legal JSP2.0 page.

JSP 2.0 starts

Before studying JSP 2.0, you need a JSP environment that supports JSP2.0 and Java Servlet 2.4 specification. Fortunately, Jakarta Tomcat 5.0 (alpha beta) supports new JSP 2.0 and servlet 2.4 specification, you can download from http://jakarta.apache.org/builds/jakarta-tomcat/release/v5.0.4-alpha/ And install Tomcat 5.0. JSP expression language

Passing information to JSP web pages is done through the JSP Scope Dature and the request parameters. An expression language (EL) specifically tailored to the web page, enhances the JSP Scope attribute to deliver information from the business logic to the JSP page. However, it is important to note that although this expression language is an important feature of JSP, it is not a general program language. It is just a data access language that can easily access and process application data without using the value of the Scriptlet or Request-Time.

Before JSP2.0, the web page can only use the expression <% = aname%> to access the system, such as the example below:

>>>

Or use the value of custom JavaBeans components:

<% = acuStomer.getaddress (). getCountry ()%>

Expression Language allows web authors to use simple syntax access objects. For example, to access a simple variable, you can write like this:

And access the nested JavaBeans property, you can write like this:

$ {acuStomer.address.country}

You may ask, is this not a syntax of JavaScript? Completely correct! If you have used JavaScript, it will be very easy because the expression language is borrowing JavaScript syntax that accesses structured data.

Note: The expression language is initially developed as part of the JSP standard tag library (JSTL) 1.0. JSTL is a standard tag library that provides support for universal, structured tasks, such as iterations, and conditions, XML documents Treatment, internationalization, and use SQL access databases. The JSTL specification is developed by the JSR 52 expert group. For an introduction to JSTL, see Faster Development with JSTL (using JSTL acceleration development).

Access application data

You can use a dot marker (.) To access application data for object properties, you can also use the square bracket operator ['Name'] to access named array elements.

Expression $ {data} represents a scope variable named DATA. You can use the order number (.) Or square bracket ([]) operator to retrieve the attribute value from the collection:

Point number operator is used to access named properties, such as expression $ {Customer.name} represents the name attribute of the scotum Customer; square bracket operator can be used to retrieve naming properties, such as $ {Customer ["name"]} in. You can also access the first item in the collection Customers through the form of $ {CUSTOMERS [0]}.

The expression language is unified to process the point and square bracket operator, so $ {Customer.Name} is equivalent to $ {Customer ["name"]} is equivalent. As you can see, the expression must be surrounded by $ {and}. The identifier of the EL is to use PageContext.FindAttribute (String) to look for its value as an attribute as an attribute. Returns NULL if this property is not found.

Operator

Expression language supports arithmetic operators, relational operators, and logical operators to complete most of the data processing operations. In addition, it also provides a special operator for testing if an object is empty. The operator is shown in Table 1. You can use the EMPTY operator to determine if a collection or string is empty. For example, only when the required naming parameter param is not given, the expression is {Empty param.name} returns true. The EMPTY operator can be used with the "!" Operator, such as $ {! Empty param.name} Returns when the required named parameter param exists.

Table 1: Expression Language Operator Operator Description Plus - Reduce * Multiply / or DIV De Inns Defolio or MOD Module (Removal) == or = Or equals! = Or! = Not equal to or GT greater than < = Or LE is less than or equal to> = or GE greater than or equal to && or AND logic and || or not logic or! Or NOT logic non-EMPTY check is empty value a? B: c condition operator

Include object

In addition to the operator, the expression language also defines some implied objects to support web page authors to access the needed application data. The implicit object defined by the expression language is shown in Table 2, and an example of using these implicit objects will be given later.

Table 2: Implied objects in the expression language implicit object content ApplicationsCope application SCOPED variable consisting of all cookies All cookies Compose Header HTTP Request Headquarters, String HeaderValues ​​HTTP Request Headquarters, String Collection InitParam All application parameter names set PageContext javax.servlet.jsp.PageContext Objects All Objects All Objects All Objects All Request parameters All request parameters All as a string collection RequestScope All request scope Collection of objects for the SESSIONSCOPE of all session ranges

Expression language example

As you say, the web page does not need to learn Java and can also use this expression language. Sample Code 1 shows some examples of expressions and the use of implicit objects.

Code Example 1: EX1.JSP

To run this example, please refer to the following steps, here we assume that Tomcat 5.0 is installed under C: /Tomcat5.0.

Switching directory to C: /TOMCAT5.0/WebApps/jsp-examples Create a new directory, name can be arbitrary, such as JSP2-Tutorial switches to JSP2-Tutorial to copy the ex1.jsp and save to the Tomcat 5 server: Point to "Start" -> Programs -> "Apache Tomcat 5.0", click "Apache Tomcat 5.0" to start Tomcat Enter http: // localhost: 8080 / jsp-examples / JSP2-Tutorial / EX1. JSP

You will see the screen similar to Figure 1. It is as simple as using an expression language!

Figure 1: JSP expression language and implicit object

Note: In this article, all JSP files are saved in the c: /tomcat5.0/webapps/jsp-examples/jsp2-tutorial directory. Fill table single case

Include object $ paran [var] can be used to read the data of the populated form. Code Example 2 gives a simple form that prompts the user to enter a name.

Code Example 2: Form.jsp

form content </ title> </ head></p> <p><Body></p> <p><H3> Fill-Out-Form </ H3> <p> <form action = "form.jsp" method = "get"> name = <input type = "text" name = "value" value = "$ {param ['Name']}> <input type = "submit" value = "submit name"></p> <p></ Form></p> <p><P> The name is: $ {param.name}</p> <p></ Body> </ html></p> <p>In this example, when the user enters the name and click the "Submit" button, the input name will display "The Name IS:" in the same page, as shown in Figure 2.</p> <p>Similarly, running this example only needs to copy form.jsp to c: /tomcat5.0/webapps/jsp-examples/jsp2-tutorial and open it with your browser.</p> <p>Figure 2: Form processing</p> <p>Define and use functions</p> <p>Expression Language allows you to define functions that can be called in an expression. The function must be written as a public static method in the public class. Once the function is defined, its signature is mapped to the label library descriptor (TLD).</p> <p>To illustrate the use of functions, we will give a simple example and add two numbers. First, you must write a Java method code for two numbers, as shown in Code Example 3, define a static method, which receives two string parameters, parsing them into integers and returns them.</p> <p>Code Example 3: Compute.java</p> <p>Package jsp2.examples.el;</p> <p>Import java.util. *;</p> <p>Public class compute {public static int add (string x, string y) {int a = 0; int b = 0; try {a = integer.parseint (x); b = integer.parseint (y);} catch (Exception e) {} return a b;}}</p> <p>After using JAVAC to compile this code, the next step will map the signature of the function to the label library. Code Example 4 illustrates how to map the ADD function to a class containing function implementations and function signs. The following will be added to where this code is added.</p> <p>Code Example 4: Function Descriptor</p> <p><Function> <description> Add x and y </ description> <name> add </ name> <function-class> jsp2.examples.el.compute </ function-class> <function-signature> int Addd (Java. Lang.string, java.lang.string) </ function-signature> </ function> Now we can write a JSP page to use this function. Code Example 5 is a form that contains two fields, and the user enters two numbers and presses the "summation" button, which will call the above function and add the two numbers, the result is displayed in the same page.</p> <p>Code Example 5: Math.jsp</p> <p><% @ taglib prefix = "my" URI = "http://jakarta.apache.org/tomcat/jsp2-example-taglib%></p> <p><Head> <title> functions </ title> </ head></p> <p><Body></p> <p><H3> add number </ h3> <p> <form action = "math.jsp" Method = "get"> x = <input type = "name =" x "value =" $ {param ["x "]}"> <br> Y = <input type = "name =" y "value =" $ {param ["y"]}> <input type = "submit" value = "add number"> </ Form></p> <p><P> The sum is: $ {my: add (param ["x"], param ["y"])}</p> <p></ Body> </ html></p> <p>To run this example:</p> <p>Copy compute.java and save it to c: /tomcat5.0/webapps/jsp-examples/web-inf/classes/jsp2/examples/El; use Javac compile compute.java; edit file C: /tomcat5.0/webapps /jsp-examples/web-inf/jsp2/jsp2-example-taglib.tld, add code segments in code sample 4 to the last </ function> tag in the file, before the </ taglib> tag; copy Math. JSP and save it to c: /tomcat5.0/webapps/jsp-examples/jsp2-tutorial; open the file with your browser.</p> <p>If everything is normal, you should see a window similar to Figure 3.</p> <p>Figure 3: Using a function</p> <p>Label processor</p> <p>The traditional label processing API in JSP 1.2 is complex due to the allowable label, but now uses the expression language to write a JSP web page that does not contain scripTlets. In the end, JSP 2.0 introduces a new label extension mechanism called "Simple Label Extension", which has two ways: Java developers can define the classes of interface javax.servlet.jsp.tagext.simpleTag; You can use the label file if you don't understand the Java webpage.</p> <p>First, look at the first way, code example 6 gives a simple label processor, and its role is just printing "this is my first tag!".</p> <p>Code Example 6: HelloTag.Java</p> <p>Package jsp2.examples.simpletag;</p> <p>Import javax.servlet.jsp.jspexception; import javax.servlet.jsp.tagext.simpletagsupport;</p> <p>Import java.io.ioException;</p> <p>/ ** * SimpleTag handler that prints "This is my first tag!" * / Public class HelloTag extends SimpleTagSupport {public void doTag () throws JspException, IOException {getJspContext (). GetOut (). Write ( "This is my first tag ! ");}}</p> <p>After the compilation is successful, the next step will define a label descriptor in the TLD, and below is an example of the label descriptor.</p> <p>Code Example 7: Label Descriptor</p> <p><tag> <description> Prints this is my first tag </ description> <name> hello </ name> <tag-class> jsp2.examples.simpletag.HelloTag </ tag-class> <body-content> EMPTY </ Body-Content> </ tag></p> <p>Finally, a JSP page file using the above label is repeated, see the code example 8.</p> <p>Code Example 8: HelloWorld.jsp</p> <p><% @ Taglib prefix = "MyTag" URI = "/ Web-INF / JSP2 / JSP2-EXAMPLE-TAGLIB.TLD"%> <html> <head> <title> Simple tag handler </ title> </ head></p> <p><Body> <H2> Simple Tag Handler </ h2> <p> <b> My first tag prints </ b>: <mytag: hello /> </ body> </ html></p> <p>To run this example:</p> <p>Copy hellotg.java and save it to c: /tomcat5.0/webapps/jsp-examples/web-inf/classes/jsp2/examples/simpletAg; use Javac to compile hellotag.java; add the label descriptor in Code Example 7 To file c: /tomcat5.0/webapps/jsp-examples/web-inf/jsp2/jsp2-example-taglib.Tld </ taglib> before </ taglib> before copying helloworld.jsp and saved to c: /tomcat5.0/ WEBAPPS / JSP-EXAMPLES / JSP2-TUTORIAL directory; open helloworld.jsp with your browser. If everything is normal, you should see a picture similar to Figure 4.</p> <p>Figure 4: Simple label processor</p> <p>Label file</p> <p>Another way to use a simple label extension mechanism is to pass the label file. The label file is a resource file, and the web author can take advantage of its JSP code, achieve the reuse of the code by customization. In other words, the tag file allows the JSP web page to create a reused tag library using the JSP syntax. The extension of the label file must be ".tag".</p> <p>To explain how easy it is to use the label file, consider the code example 9. That's right, this is a label file!</p> <p>Code Example 9: Greetings.tag</p> <p>Hello there. How are you doing?</p> <p>Once the label file is defined, this customized function can be used in the written written in the JSP page. For example, the JSP page in Code Example 10.</p> <p>Code Example 10: Chat.jsp</p> <p><% @ taglib prefix = "tags" tagdir = "/ web-inf / tags"%> <html> <head> <title> JSP 2.0 Examples - Hello World Using a tag file </ title> </ head> <body > <H2> Tag File Example </ h2> <p> <b> The output of my first tag file is </ b>: <tags: greetings /> </ body> </ html></p> <p>To run this example:</p> <p>Copy the label file Greetings.tags and save it in a c: /tomcat5.0/webapps/jsp-examples/web-inf/tags directory; copy the JSP web file char.jsp and save it in c: /tomcat5.0/webapps/jsp -examples / jsp2-tutorial directory; open the chat.jsp file with your browser. If everything is normal, you should see a window similar to Figure 5.</p> <p>Figure 5: Simple label file</p> <p>Note: It is important to note that there is no TLD to be written here, but create a tag file and put it in a special directory, then import and use it directly with Taglib instructions.</p> <p>Another label file</p> <p>The label file can be used as a template. Consider the tag file DISPLAY.TAG in Code Example 11, this example is rewritten in an example of the panel in Tomcat 5.0. The command attribute is similar to the <attribute> element in the TLD, allowing a declared action attribute.</p> <p>Code Example 11: Display.tag</p> <p><% @ attribute name = "color"%> <% @ attribute name = "bgcolor"%> <% @ attribute name = "title"%> <table border = "0" bgcolor = "$ {color}"> <{color}> < Tr> <TD> <b> $ {title} </ b> </ td> </ tr> <tr> <td bgcolor = "$ {bgcolor}"> <jsp: dobody /> </ td> </ Tr> </ table></p> <p>Code Example 12 gives a simple JSP page using the above label.</p> <p>Code Example 12: Newsportal.jsp</p> <p><% @ taglib prefix = "tags" tagdir = "/ web-inf / tags"%> <html> <head> <title> another tag file example </ title> </ head> <body> <h2> News Portal : Another Tag File Example </ H2> <Table Border = "0"></p> <p><Tr Valign = "TOP"> <TD> <tags: display color = "# ff0000" bgcolor = "# ffc0c0" title = "travel"> Last French Concorde arrives in ny another travel headline YET Another Travel Headline </ tags: display> </ td> <td> <tags: display color = "# 00fc00" bgcolor = "# c0ffc0" title = "technology"> Java for in-flight entertainment < BR> Another Technology Headline <BR> Another Technology Headline <BR> </ tags: display> </ TD> <TD> <tags: display color = "# ffcc11" bgcolor = "# ffffcc" title = "Sports"> American FOOTBALL NBA SOCCER </ tags: display> </ td> </ tr> </ table> </ body> </ html> To run this example:</p> <p>Copy file display.tag and save it under C: /Tomcat5.0/webapps/jsp-examples/web-inf/tag; copy file newsportal.jsp and save to C: /tomcat5.0/webapps/jsp-examples/jsp2 -Tutorial; open the NewSportal file with your browser.</p> <p>The result should be obtained as a picture similar to Figure 6.</p> <p>Figure 6: Tag files as templates</p> <p>in conclusion</p> <p>JSP 2.0 makes it easier than before, although "java" appears in JSP, although "java" appears in JSP, but use JSP2.0, web page authors can develop a new dynamic web page. The examples in this article illustrate how easy it is to develop dynamic web pages using JSP2.0. More information</p> <p>Fast Track JSP 1.2 JavaServer Pages Technology JavaServer Pages Specification (JSR 152) The Tomcat 5 Servlet / JSP Container JSP Developers Forum JavaServer Pages Standard Tag Library (JSTL) Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0) Acknowledgments Special thanks to Sun Microsystems, Inc. Gregory Murry and Mark Roth, their feedback helped me improve this article.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-96369.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="96369" 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.034</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 = 'JfUsub681TOLomBYkt2N1hZgW_2FpNa7w6xbnX6e4LZmYDb_2BN84L_2FsfNH39UjMywN_2F0eIy7qbjvLDcaB_2F5og55vA_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>