JSP 2.0 is really BT! But it looks very convenient. (Developing Web Applications with JavaServer Pages 2.0)

zhaozj2021-02-16  43

By Qusay H. Mahmoudjuly 2003

JavaServer Pages (JSP) technology, which abstracts servlets to a higher level, is an open, freely-available specification developed by the Java Community Process (JCP) for generating dynamic content, and a key component of the Java 2 Enterprise Edition (J2EE) Spectation. Many Commercially Available Application Servers (Such As BEA WebLogic, IBM WebSphere, Live Jrun, and ORION) Support JSP Technology.

JSP technology is being used everywhere on the Web including airline reservation systems, banking systems, and shopping. The new release, Version 2.0, is an upgrade to JSP 1.2 with several interesting new features. The objective of JSP 2.0 is to make the task of Dynamic Web Pages Easier Than Ever WITHOUT HAVING to Learn The Java Programming Language.

This Article:

Provides a fast track code intensive tutorial to get started with JSP 2.0 Describes the new features in JSP 2.0 Offers a flavor of the effort involved in developing applications using JSP 2.0 Provides sample code that you can adapt for your own applications

If you are new to jsp, IT Might Be a good idea to start directly with jsp 2.0. However, if you wish to Learn About JSP 1.2 You May Want To Start With this JSP Tutorial.

JSP 2.0

JSP 2.0 is an upgrade to JSP 1.2 with several new interesting features that make the lives of Web application designers and developers easier. The objective of JSP 2.0 is to make JSP easier to use than ever, and more importantly to be used without having to learn ........................

In Addition To Several Other Improvements, The New Key Features That Have Been Introduces IN JSP 2.0 Are:

A simple expression language (EL), which can used to easily access data from JSP pages. The expression language simplifies writing scriptless JSP-based applications without using Java scriptlets or Java expressions. New syntax for defining reusable custom actions using JSP technology directly. The syntax is delivered into .tag and .tagx files which can be written by developers and page authors. The XML syntax has been improved substantially. The new standard filename extensions (.tagx for tag files and .jspx for JSP files) have been added. In this Article I Concentrate On The Expression Language, The Simplified Tag API, AND TAG FILES. I Believe Existing JSP Developers Will Find these Key Features To Be Very Interesting and useful.

Why the jump from 1.2 to 2.0?

The version number was originally listed as 1.3 in the Java Specification Request (JSR 152). However, given that the new features would have a deep impact on the development model of JSP applications as you will see later, the Expert Group felt it was necessary to upgrade the major version number to 2.0 since this would reflect the impact more appropriately. Also, the new version number will help draw the attention of developers to these new interesting features. The good news is that all valid JSP 1.2 pages are also valid JSP 2.0 pages.

Getting Started with JSP 2.0

In order to get started with JSP 2.0, you need a JSP container that supports the JSP 2.0 specification and the Servlet 2.4 specification Java. Luckily, Jakarta Tomcat 5.0 (Alpha release) supports the new JSP 2.0 and Servlet 2.4 specifications. Download and install Tomcat 5.0.

The JSP Expression Language

Information to be passed to JSP pages is communicated using JSP scoped attributes and request parameters. An expression language (EL), which is designed specifically for page authors, promotes JSP scoped attributes as the standard way to communicate information from business logic to JSP pages. note, however, that while the EL is a key aspect of the JSP, it is not a general purpose programming language. Rather, it is simply a data access language, which makes it possible to easily access (and manipulate) application data without having To use scripTlets or request-time expression value.prior to JSP 2.0, a page author had to use the expression <% = aname%> To access the value of a system, as in the folowing example:

>>>

Or The Value of a Custom JavaBeans Component:

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

An Expression Language Allows A Page Author To Access An Object Using A Simplified Syntax. For Example, To Access A Simple Variable, You CAN Use Something Like:

And to Access A Nested JavaBeans Property, You Would Use Something Like:

$ {acuStomer.address.country}

But, you might ask, is not this JavaScript syntax? You are absolutely right! If you've worked with JavaScript, you will feel right at home, because the EL borrows the JavaScript syntax for accessing structured data.

Note: The Expression Language was originally developed as part of the JavaServer Pages Standard Tag Library (JSTL) 1.0, which is a standard tag library that provides support for common, structural tasks, such as iteration and conditionals, processing XML documents, internationalization, and Database Access Using The Structured Query Language (SQL). The JSTL Specification IS Being Developed by The JSR 52 Expert Group. For a Tutorial ON JSTL, PLEASE Seeter development with jstl.

Accessing Application Data

You CAN Access Application Data Either As a Property of An Object, Using The Dot (.) Operator, or a named Array Element Using The Bracket ['Name'] Operator.

The expression $ {data} represents the scoped variable name from collections using each dot (.) Or bracket ([]) Operator:

The dot (.) Operator is used to retrieve a named property. For example, the expression $ {customer.name} indicates the name property of the customer scoped variable. The bracket operator ([]) can be used to retrieve a named property AS IN $ {Customer ["name"]}. The Bracket Operator Can Also Be Used AS $ {Customers [0]} TO REFER TO The First Item In The Customers Collection.

THE EXPRESSION LANGUAGE UNIFIES The Treatment of Dot (.) Operators. Therefore, $ {Customer.Name} Is Equivalent to $ {Customer ["Name"]}. As you can see, All el Expressions Must Be ENCLOSED BETWEEN $ {and}.

The el evatates an identifier by looking up its value as an attribute using pagecontext.Findattribute (string). If the attribute is not found, Null is returned.

Operators

The EL supports arithmetic, relational, and logical operators to handle the most common data manipulations. In addition, a special operator for testing if an object is empty is provided. The operators are shown in Table 1. You can use the empty operator to determine whether a collection or a string is empty or null. For example, $ {empty param.name} will be true only if the request parameter named param is not present. The empty operator can be combined with the! operator, as in the expression $ {! empty param.name}, which evaluates to true if the request parameter named param is present.Table 1: Expression language operatorsOperatorDescription Addition-Subtraction * Multiplication / or divDivision% or modModulus (Remainder) == or = Equality =! ! or = Inequality or gtGreater than <= or leLess than or equal to> = or geGreater than or equal to && or andLogical AND || or orLogical oR or notBoolean complementemptyCheck for empty valuea b:!? cConditional operator

Implicit Objects

In addition to operators, the EL defines implicit objects to support access to application data that is of interest to page authors. The implicit objects defined by the EL are shown in Table 2. An example of how to use some of these implicit objects is provided Later.

Table 2: Implicit objects provided by the expression languageImplicit ObjectContentapplicationScopeA collection of scoped variables from applications scopecookieA collection of all cookiesheaderHTTP request headers as stringsheaderValuesHTTP request headers as collections of stringsinitParamA collection of all application parameter namespageContextThe javax.servlet.jsp.PageContext object for the current pagepageScopeA collection of all page scope objectsparamA collection of all request parameters as stringsparamValuesAll request parameters as collections of stringsrequestScopeA collection of all request scope objectssessionScopeA collection of all session scope objectsEL Example

As you can Tell, Web Page Authors Can Use The Expression Language WITHOUT HAVING to Learn Java. Code Sample 1 Shows Some El Expressions As Well as The Use of Explicit Objects.

Code Sample 1: EX1.JSP

Expression Language Examples </ TITLE> </ HEAD> <BODY> <H3> JSP Expression Language Examples </ H3> <P> The following table illustrates some EL expressions and implicit objects: <TABLE Border = "1"> <TD> <TD> <B> Expression </ b> </ td> <td> <b> value </ b> </ td> </ thead> <tr> <td> / $ {2 5} </ td> <td> $ {2 5} </ td> </ td> <tr> <td> / $ {4/5} </ td> <td> $ {4 / 5} </ td> </ tr> <tr> <td> / $ {5 div 6} </ td> <td> $ {5 div 6} </ td> </ tr> <tr> <TD > / $ {5 MOD 7} </ td> <td> $ {5 mod 7} </ td> </ tr> <tr> <td> / $ {2 <3} </ td> <td> $ {2 <3} </ td> </ tr> <tr> <td> / $ {2 gt 3} </ td> <td> $ {2 gt 3} </ td> </ tr> <tr> <TD> / $ {3.1 Le 3.2} </ td> <td> $ {3.1 Le 3.2} </ td> </ tr> <tr> <td> / $ {(5> 3)? 5: 3} </ Td> <td> $ {(5> 3)? 5: 3} </ td> </ tr> <tr> <td> / $ {header ["host"]} </ td> <td> $ {header ["Host"]} </ td> </ tr> <tr> <td> / $ {header ["user-agent"]} </ td> <td> $ {header ["User-Agent "]} </ Td> </ tr> </ table> </ body> </ html> in Order to Run this, do the following. Here I Assute Tomcat 5.0 IS Installed At C: /TOMCAT5.0</p> <p>Change directory to c: /Tomcat5.0/webapps/jsp-examples Create a directory and name it whatever you like, let's say jsp2-tutorial Change directory to jsp2-tutorial Copy the ex1.jsp from this article and save it there Start the tomcat 5 server by going to Start-> Programs-> Apache tomcat 5.0-> Start tomcat In your Web browser, enter http: // localhost: 8080 / jsp-examples / jsp2-tutorial / ex1.jspYou should something similar to Figure 1 It is what simple to use the expression language @ ip.</p> <p>Figure 1: JSP Expression Language and Implicit Objects</p> <p>NOTE: IN this article, All JSP Pages Will Be Saved Under</p> <p>C: / Tomcat5.0/webapps/jsp-examples/jsp2-tutorial.</p> <p>Fill-Out-Form Example</p> <p>.</p> <p>Code Sample 2: form.jsp</p> <p><Html> <head> <title> form content </ title> </ head> <body> <h3> Fill-out-form </ h3> <p> <form action = "/ wevoloper / technicalArticles / JavaServerPages / JSP20 /form.jsp "method =" get "> name = <input type =" name = "name" value = "$ {param ['name']}> <input type =" Submit "Value =" Submit Name "> </ form> <p> the name is: $ {param.name} </ body> </ html></p> <p>In this Example, When a User Enters a name and clicks the "Submit Name" Button, The name Entered Will Be Displayed on The Same Page Next To "The name is:" as shown in figure.</p> <p>Again, in Order To Run this Example, Simply Copy Form.jsp To c: /tomcat5.0/webapps/jsp-examples/jsp2-tutorial and request what page from a web browser.figure 2: Handling Forms</p> <p>Developing and use functions</p> <p>The expression language allows you to define functions that can be invoked in an expression. Functions must be programmed as a public static method in a public class. Once the function is developed, its signature is mapped in a Tag Library Descriptor (TLD).</p> <p>To illustrate the use of functions, I use a simple example to add two numbers. First we write the Java code for the method to add two numbers. Code Sample 3 shows a static method that accepts two Strings, parses them to integers, and returns Their sum.</p> <p>Code Sample 3: Compute.java</p> <p>Package jsp2.examples.el; import java.util. *; 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>Once this is successfully compiled using javac, the next step is to map the function's signature in the tag library. Code Sample 4 shows how to map the add function to the class containing the implementation of the function and the signature of the function. I will Tell you where to add this.</p> <p>Code Sample 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></p> <p>Now, we can write the JSP page that uses the function. Code Sample 5 shows a form with two fields. The user enters two numbers and when the "Add Numbers" button is clicked, the function is called to add the numbers. The result Is Displayed on The Same Page.code Sample 5: Math.jsp</p> <p><% @ taglib prefix = "my" URI = "http://jakarta.apache.org/tomcat/jsp2-example-taglib%> <head> <title> functions </ title> </ head> <body> < H3> add number </ h3> <p> <form action = "/ wevoloper / technicalArticles / javaServerPages / JSP20 / math.jsp" method = "get"> x = <input type = "text" name = "x" Value = "$ {param [" x "]}> <br> Y = <input type =" text "name =" y "value =" $ {param ["y"]}> <input type = Submit "value =" add number "> </ form> <p> The sum is: $ {my: add (param [" x "], param [" y "])} </ body> </ html></p> <p>To Run this Example:</p> <p>Copy Compute.java and save it at: c: /tomcat5.0/webapps/jsp-examples/web-inf/classes/jsp2/examples/classes/jspute.java using javac edit the file c: /tomcat5.0/webapps /jsp-examples/web-inf/jsp2/jsp2-example-taglib.tld and append the snippet of code in code sample 4 after the last </ function> in the file and before </ taglib> Copy Math.jsp To C : /Tomcat5.0/webapps/jsp-examples/jsp2-tutorial request the jsp file math.jsp from a web browser</p> <p>If All Goes Well, You Should See Something Similar To Figure 3.</p> <p>Figure 3: using functions</p> <p>Tag Handlers</p> <p>The APIs for classic tag handlers in JSP 1.2 is complicated by the allowance of scriptlets in the body of tags. With the expression language, however, it is now feasible to develop scriptless JSP pages. To this end, JSP 2.0 has introduced a new type of tag extension called a Simple Tag Extension that can be used in one of two ways: Java developers: by defining a class that implements the javax.servlet.jsp.tagext.SimpleTag interface Page authors who do not know Java:. by using tag Files.</p> <p>Here is an example of the first approach. Code Sample 6 Shows A Simple Tag Handler That Prints this is my first tag !.</p> <p>Code Sample 6: Hellotag.java</p> <p>package jsp2.examples.simpletag; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; / ** * 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>Once this is successfully compiled, The next step is to define a tag descriptor in a tld. Code Sample 7 Shows A Sample Tag Descriptor:</p> <p>Code Sample 7: Tag 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>And Finally, Code Sample 8 Shows A JSP Page That Uses The Tag i Have Just Developed.</p> <p>Code Sample 8: HelloWorld.jsp</p> <p><% @ Taglib prefix = "MyTag" URI = "/ Web-INF / JSP2 / JSP2-EXAMPLE-TAGLIB.TLD"%> <html> <head> <title> Simple tag handler </ title> </ head> < Body> <H2> Simple Tag Handler </ h2> <p> <b> My first tag prints </ b>: <mytag: hello /> </ body> </ html> to run this example:</p> <p>Copy HelloTag.java and save it under C: /Tomcat5.0/webapps/jsp-examples/WEB-INF/classes/jsp2/examples/simpletag Compile the HelloTag.java using javac Append the tag description shown in Code Sample 7 to the End of the file: c: /tomcat5.0/webapps/jsp-examples/web-inf/jsp2/jsp2-example-taglib.tld, before </ taglib> Copy HelloWorld.jsp and save it at: C: / Tomcat5 .0 / WebApps / JSP-EXAMPLES / JSP2-Tutorial Request HelloWorld.jsp from A Web Browser</p> <p>IF all goes well you shouth see Something Similar To Figure 4.</p> <p>Figure 4: Simple Tag Handler EXAMPLE</p> <p>Tag file</p> <p>The other way of using the Simple Tag Extension is through the use of tag files. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable through a custom action. In other Words, Tag Files Allow JSP Page Authors To Create Reusable Tag Libraries Using JSP SYNTAX. The Required File Extension for a Tag File Is .tag.</p> <p>To Demonstrate How Easy this Is, Consider The Tag File In Code Sample 9. That Is Right, This Is A Tag File!</p> <p>Code Sample 9: Greetings.tag</p> <p>Hello there. How are you doing?</p> <p>Once a Tag File Has Been Defined, you can write a JSP page That Uses Custom Action. AS An Example, Consider The JSP Page In Code Sample 10.</p> <p>Code Sample 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> to run this example:</p> <p>Copy The Tag File, Greetings.tag, And Save It Under C: /Tomcat5.0/webapps/jsp-examples/web-inf/tags copy the JSP page, chat.jsp, and save it at c: /tomcat5.0 / WebApps / JSP-Examples / JSP2-Tutorial Request the chat.jsp File from A Web Browser</p> <p>If All Goes Well, You Should See Something Similar To Figure 5.</p> <p>Figure 5: Simple Tag File Example</p> <p>Note: What is important to notice here is what i Did Not NETINGS TAG. I Just Created The Tag File In a Special Directory, And Imported It Using The Taglib Directive, And Used IT!</p> <p>Another Tag File EXAMPLE</p> <p>Tag files can be used as a template. Consider the tag file, display.tag, shown in Code Sample 11. This example is adapted from the panel example that comes with Tomcat 5.0. The attribute directive is analogous to the <attribute> element in The Tld; It Allows for the Declaration of custom action attributes.</p> <p>Code Sample 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 Sample 12 Shows A Simple JSP Page That Uses The Display Tag.code Sample 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"> <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> iNother Technology Headline <br> </ tags: display> </ td> <td> <tags: display color = "# ffcc11" bgcolor = "# fffcc" title = "sports"> American football NBA SoCCER </ tags: display> </ td> </ tr> </ table> </ Body> </ html></p> <p>To Run this Example:</p> <p>Copy the file display.tag and save it Under C: /tomcat5.0/webapps/jsp-examples/web-inf/tag copy the file newsportal.jsp and save it under c: /tomcat5.0/webapps/jsp-examples / JSP2-Tutorial Request the newsportal.jsp from A Web Browser</p> <p>Now, you willtee 6. Similar To Figure 6.</p> <p>Figure 6: Using Tag File As a Template</p> <p>Conclusion</p> <p>JSP 2.0 makes is easier than ever to rapidly develop and easily maintain dynamic Web pages. Despite the fact the word "Java" appears in JavaServer Pages, with JSP 2.0 page authors can develop innovative dynamic Web pages without having to learn the Java programming language. THE EXAMPLES SHOWN THROUGHOUGHOTICLE DEMONSTRATE HOW Easy It Is To Get Started Using The New Features in JSP 2.0 To Develop Dynamic Web Pages.for 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)</p> <p>Acknowledgments</p> <p>Special Thanks to Gregory Murray and Mark Roth of Sun Microsystems, Whose Feedback Helped Me Improve this Article.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-20478.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="20478" 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.065</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 = 'uckxTRVwSdLvqBz6Y9IA_2F0Jc8D77qw0ZvMpIj0wvTctf_2B9tyyq6wcyAMpaoDBSMGGlc7dnJpyxDeXBlDxlRDpQ_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>