Developing Web applications with JSP 2.0

Source: Internet
Author: User
Tags add numbers arithmetic operators logical operators tld apache tomcat
Developing Web applications with JSP 2.0


Author: Qusay H. Mahmoud
July 2003



The JSP (JavaServer Pages) technology is a further abstraction of the servlet, developed by JCP (Java Community Process), is an open, freely accessible specification for generating dynamic content, and is also Java 2 Enterprise Edition) is an important part of the specification. Many business application servers such as Bea WebLogic, IBM WebSphere, Live JRun, and Orion support JSP technology.



JSP technology is applied everywhere on the web, from ticket reservation systems to banking systems to shopping systems. The new release of version 2.0 is an upgrade to JSP1.2, adding some interesting new features. The goal of JSP2 is to make the design of dynamic Web pages easier and without learning the Java programming language.



This article includes: Provides a tutorial with rich sample code to familiarize you with the new features of the JSP2.0 introduction JSP2.0 provides some examples of how you can use JSP2.0 to develop your application, and make a few changes to the code to use for your own application.



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

JSP 2.0



JSP 2.0 is an upgrade to JSP 1.2, adding several interesting new features that make it easier for Web application designers and developers to work. The goal of JSP 2.0 is to be easier to use than it used to be, and, more importantly, to use it without learning the Java language itself. It adds a new extension mechanism called Simpletag to simplify the tagging API (Tag API).



Among other improvements, the most important new features introduced in JSP 2.0 include a simple expression language (EL) that can be used to easily access data from JSP pages, which simplifies the authoring of JSP-free applications without the need to use Java Scriptlet or Java expression; a new syntax for directly using JSP technology to define reusable custom behavior that uses. tag and. tagx files that can be written by developers or web authors; the 3XML syntax has been substantially improved, Added a new standard file name extension (. tagx for tag files,. jspx for JSP files).



This article mainly discusses the expression language, the simplified label API, and the label file. It is believed that the current JSP developers will find these important features interesting and useful. 

why to jump from 1.2 to 2.0.



The version number in the Java Specification request (JSR 152) is initially set to 1.3. But as you'll see later, because these new features have such a profound impact on the development model of the JSP application, the group feels the need to upgrade the major version number to 2.0 in order to fully reflect the impact. In addition, the new version number helps to draw developers ' attention to these interesting new features. Thankfully, all legitimate JSP1.2 pages are also legitimate JSP2.0 pages .

  JSP 2.0 Start



Before you start learning JSP 2.0, you need a JSP environment that supports the JSP2.0 and Java Servlet 2.4 specification. Fortunately, the Jakarta Tomcat 5.0 (Alpha Beta) supports the new JSP2.0 and servlet 2.4 specification, which can be from http://jakarta.apache.org/builds/jakarta-tomcat/ release/v5.0.4-alpha/Download and install Tomcat 5.0.

  JSP Expression Language



Passing information to a JSP Web page is done through the JSP scoped properties and request parameters. An expression language (EL) tailored specifically for Web authors promotes the JSP scoped attribute as a standard way of delivering information from business logic to JSP pages. However, note that although this expression language is an important feature of JSP, it is not a common programming language. It is simply a data access language that makes it easy to access and process application data without the use of scriptlet or the value of a request-time (request-time) expression.



Before JSP2.0, Web page authors can only use the expression <%= aname%> access the value of the system, such as the following example:



<sometags:atag attribute= "<%= pagecontext.getattribute (" Aname ")%>" >



Or use the value of the custom JavaBeans component:



<%= acustomer.getaddress (). Getcountry ()%>



An expression language allows Web page authors to access objects using simple syntax. For example, to access a simple variable, you can write as follows:



<sometags:atag attribute= "${aname}" >



To access nested JavaBeans properties, you can write as follows:



${acustomer.address.country}



You might ask, is this not JavaScript syntax? Absolutely right. If you've ever used JavaScript, you'll feel very relaxed because the expression language borrows the JavaScript syntax to access structured data.



Note: The expression language was originally developed as part of the JSP Standard Tag Library (JSTL) 1.0, and JSTL is a standard tag library that provides support for common, structured tasks such as iterations and conditions, XML document processing, internationalization, and access to databases using SQL. The JSTL specification was developed by the JSR 52 expert group. For an introduction to JSTL, see faster Development with JSTL (Accelerated development with JSTL). 

Accessing Application Data



You can use the dot operator (.) To access the application data as an object property, or you can access the named array element by using the bracket operator [' name '].



An expression ${data} represents a scoped variable named data. You can retrieve property values from the collection using the point number (.) or the bracket ([]) operator: The dot operator is used to access a named property, such as an expression ${customer.name} that represents the Name property of the scoped variable customer; The bracket operator can be used to retrieve a named property. For example, in ${customer["name"}. You can also access the first item in the collection customers through the form ${customers[0]}.



The expression language unifies the processing of the dot and bracket operators, so ${customer.name} is equivalent to ${customer[' name '}. As you can see, expressions must be surrounded with ${and}.



El's identifier is evaluated by using Pagecontext.findattribute (String), which is used as an attribute to find its value. If the property is not found, NULL is returned. 

operator



The expression language supports arithmetic operators, relational operators, and logical operators to accomplish most data processing operations. In addition, it provides a special operator for testing whether an object is empty. The operator is shown in table 1. You can use the empty operator to determine whether a collection or string is empty. For example, the expression ${empty Param.name} returns true only if the requested named parameter param is not given. The empty operator can be associated with the "!" Operators, such as ${!empty Param.name} returns True when the required named argument param exists.


Table 1: Expression language operators

Operator

Description

+

Add

-

Reducing

*

By

/or Div

Except

% or mod

Modulus (remainder)

= = or =

Equals

!= or!=

Not equal to

< or LT

Less than

> or GT

Greater than

<= or Le

Less than or equal to

>= or GE

Greater than or equal to

&& or

Logic and

|| OR OR

Logical OR

! Or not

Logical non

Empty

Check for null values

A? B:c

Conditional operator

suppressed Objects


In addition to operators, the expression language defines some hidden objects to enable Web page authors to access the required application data. The implied object of the expression language definition is shown in table 2, followed by an example of using these suppressed objects.


Table 2: Implied objects in the expression language

Suppressed objects

Content

Applicationscope

A collection of application-scoped scoped variables

Cookies

A collection of all cookies

Header

HTTP request headers, strings

Headervalues

HTTP request headers, string collection

Initparam

A collection of all application parameter names

PageContext

Javax.servlet.jsp.PageContext object for the current page

Pagescope

Collection of all objects within a page range

Param

A collection of all request parameter strings

Paramvalues

All request parameters as collection of strings

Requestscope

Collection of all request-scoped objects

Sessionscope

A collection of all session-scoped objects

An example of an expression language


As you have said, Web authors can use this expression language without learning java. Example code 1 shows examples of some expressions and the use of suppressed objects.



code Example 1: ex1.jsp



To run this example, please refer to the following steps, where we assume that Tomcat 5.0 is installed under c:/tomcat5.0. Switch directories to c:/tomcat5.0/webapps/jsp-examples create a new directory, the name can be arbitrary, such as jsp2-tutorial switch to jsp2-tutorial to copy and save ex1.jsp to the directory to start Tomcat 5 server: Point to start-> program-> "Apache Tomcat 5.0", click "Apache Tomcat 5.0" to start Tomcat in the browser http://localhost:8080/ jsp-examples/jsp2-tutorial/ex1.jsp



You will see a picture similar to that shown in Figure 1. Using an expression language is as simple as that.




Figure 1:jsp Expression language and implied object



Attention : In this article, all of the JSP files are saved in the C:/tomcat5.0/webapps/jsp-examples/jsp2-tutorial directory.

  Fill out a form example



Suppressed object $paran[var] can be used to read data that fills a form. code Example 2 gives a simple form that prompts the user to enter a name.



code Example 2: form.jsp


<HTML>
<HEAD>
<title>form content</title>
</HEAD>

<BODY>

<H3>Fill-out-form</H3>
<P>
<form action= "form.jsp" method= "Get" >
     Name = <input type= "text" name= "name" value= "${param[' name ']}" >
                    <input type= "Submit" value= "Submit Name" >

<P>
The Name is: ${param.name}
</BODY>
</HTML>


In this example, when the user enters a name and clicks the Submit button, the name that is entered appears after the word "The name is:" In the same page, as shown in Figure 2.



Again, running this example simply copies the form.jsp to the c:/tomcat5.0/webapps/jsp-examples/jsp2-tutorial and opens it in the browser.




Figure 2: Form processing definitions and usage functions



The expression language allows you to define a function that can be called in an expression. The function must be written as a public static method in the public class. Once a function is defined, its signature (signature) is mapped to a tag library descriptor (TLD).



To illustrate the use of functions, we give a simple example of adding two numbers. First you write Java method code that asks for the sum of two, as shown in code example 3, where a static method is defined that receives two string parameters, resolves them to integers, and returns their sum.



code Example 3: Compute.java


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);
        
            return a + B;
     }
}


After compiling this code successfully with Javac, the next step is to map the signature of the function to the tag library. Code example 4 shows how to map the Add function to a class that contains function implementations and function signatures. The next section explains where to add this code.



code Example 4: function descriptor


    <function>
            <description>add x and Y</description>
            <name>add</name>
            <function-class>jsp2.examples.el.compute
                    </function-class>
            <function-signature>int
                    Add (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 when a user enters two digits and presses the sum button, the above function is called and the two numbers are added, and the results are displayed on the same page.



code Example 5: math.jsp


        Uri= "Http://jakarta.apache.org/tomcat/jsp2-example-taglib%>
<HEAD>
<TITLE>Functions</TITLE>
</HEAD>
<BODY>

<P>
The sum is: ${my:add (param["x"],param["Y"])}
</BODY>
</HTML>


To run this example: Copy the Compute.java and save it to the c:/tomcat5.0/webapps/jsp-examples/web-inf/classes/jsp2/examples/el; Compile Compute.java using Javac; Edit File c:/tomcat5.0/webapps/jsp-examples/web-inf/jsp2/ JSP2-EXAMPLE-TAGLIB.TLD, add the code snippet in code example 4 to the,</taglib> tag after the last </function> tag in the file; copy math.jsp and save to c:/ tomcat5.0/webapps/jsp-examples/jsp2-tutorial, open the file in a browser.



If everything works, you should see a window similar to that shown in Figure 3.




Figure 3: Using the Function label processor



The traditional label processing API in JSP 1.2 is complicated by allowing the tag body to contain scriptlet, but now it is possible to write a JSP Web page that contains no scriptlet by using an expression language. Finally, JSP 2.0 introduces a new tag extension mechanism called "simple tag extension", which is used in two ways: Java developers can define classes that implement Interface Javax.servlet.jsp.tagext.SimpleTag; Web page writers who don't know Java can use tag files.



First, look at the first way, code example 6 gives a simple label processor, which is simply to print "This is I-tag! ”。



code example 6: Hellotag.java


Package Jsp2.examples.simpletag;
Import javax.servlet.jsp.JspException;
Import Javax.servlet.jsp.tagext.SimpleTagSupport;
Import java.io.IOException;
/**
  * Simpletag handler that prints ' This was my I-tag! '
  */
  public class Hellotag extends Simpletagsupport {
        public void Dotag () throws Jspexception, IOException {
                Getjspcontext (). Getout (). Write ("This is me-a-tag!");
        }
}


Once the compilation is successful, the next step is to define a tag descriptor in the TLD, followed by an example of a label descriptor.



code example 7: Label descriptor


    <tag>
        <description>prints This is my tag</description>
        <name>hello</name>
        <tag-class>jsp2.examples.simpletag.HelloTag</tag-class>
        <body-content>empty</body-content>
    </tag>


Finally, write a JSP page file using the label above, see code example 8.



code Example 8: helloworld.jsp


<%@ taglib prefix= "MyTag" uri= "/web-inf/jsp2/jsp2-example-taglib.tld"%>
<HTML>
<HEAD>
<title>simple Tag handler</title>
</HEAD>
<BODY>


To run this example: Copy the Hellotg.java and save it to the C:/tomcat5.0/webapps/jsp-examples/web-inf/classes/jsp2/examples/simpletag; Use Javac to compile Hellotag.java; Add the tag descriptor in code example 7 to the file c:/tomcat5.0/webapps/jsp-examples/web-inf/jsp2/ Before </taglib> in jsp2-example-taglib.tld; copy helloworld.jsp and save to C:/tomcat5.0/webapps/jsp-examples/ Jsp2-tutorial directory; open helloworld.jsp in Browser.



If everything works, you should see something like the picture shown in Figure 4.




Figure 4: Simple label processor label file



Another way to use the simple tag extension mechanism is through the tag file. A tag file is a resource file that a Web page author can use to extract a section of JSP code that enables the reuse of code through custom functions. In other words, the tag file allows JSP page authors to create reusable tag libraries using JSP syntax. The label file extension must be ". Tag".



To illustrate how easy it is to use a label file, consider code example 9. Yes, this is a tag file.



code Example 9: Greetings.tag


Hello there. How are you doing?


Once you have defined the label file, you can use this custom feature in the authoring of JSP pages. For example, the JSP page in code example 10.



code sample: chat.jsp


<%@ taglib prefix= "tags" tagdir= "/web-inf/tags"%>
<HTML>
<HEAD>
<TITLE>JSP 2.0 Examples-hello World Using a Tag file</title>
</HEAD>
<BODY>


To run this example: Copy the tag file greetings.tags and save it in the C:/tomcat5.0/webapps/jsp-examples/web-inf/tags directory, copy the JSP page file char.jsp and save it in c:/ Tomcat5.0/webapps/jsp-examples/jsp2-tutorial directory; open chat.jsp file in browser.



If everything works, you should see a window similar to that shown in Figure 5.







Figure 5: A simple label file



Note : It is important to note that there is no TLD written for the greeting tag, but instead creates a tag file and places it in a special directory, and then imports it using the taglib instruction and uses it directly. Another example of a tag file



The label file can be used as a template. Consider the tag file Display.tag in code example 11, which is rewritten based on the example of the panel in Tomcat 5.0. The instruction attribute is similar to the <attribute> element in TLD, allowing the declaration of custom Action attributes.



code example: Display.tag


<%@ attribute name= "COLOR"%>
<%@ attribute name= "bgcolor"%>
<%@ attribute name= "title"%>
<table border= "0" bgcolor= "${color}" >
    <TR>
         <TD><B>${title}</B></TD>
     </TR>
    <TR>
        <TD bgcolor= "${bgcolor}" >
            <jsp:doBody/>
        </TD>
    </TR>
</TABLE>


Code Example 12 gives a simple JSP page that uses the label above.



code sample: newsportal.jsp


<%@ taglib prefix= "tags" tagdir= "/web-inf/tags"%>
<HTML>
<HEAD>
<title>another Tag File example</title>
</HEAD>
<BODY>


To run this example: 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 to c:/tomcat5.0/ Webapps/jsp-examples/jsp2-tutorial, open the Newsportal file in the browser.



The result should be a picture similar to Figure 6.



Figure 6: Using the label file as a template conclusion



JSP 2.0 makes it easier to quickly develop and maintain dynamic Web pages, although the word "Java" appears in JSPs, but with JSP2.0, web authors can develop new dynamic Web pages without learning the Java programming language itself. The examples in this article illustrate how easy it is to develop dynamic Web pages using the new features of JSP2.0. More Information Fast Track JSP 1.2 JavaServer pages Technology JavaServer pages specification (JSR 152) The Tomcat 5 servlet/jsp JSP developers Forum JavaServer Pages Standard Tag Library (JSTL)



Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0) Thanks



Thanks in particular to Sun Microsystems's Gregory Murry and Mark Roth, their feedback helped me improve the article.


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.