Developing Web applications with JSP 2.0

Source: Internet
Author: User
Tags add numbers define arithmetic operators empty expression functions new features apache tomcat
The js|web| program JSP (JavaServer Pages) technology is a further abstraction of the servlet, developed by the JCP (Java Community Process), an open, freely accessible specification for generating dynamic content, It is also an important part of the Java 2 Enterprise Edition 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.

The content of this article includes:

Provide a tutorial with rich sample code to familiarize you with JSP2.0
Introducing new features of JSP2.0
Provides some experience with using JSP2.0 to develop applications
Some sample code is given, and the code can be slightly modified 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 by JSP 2.0 include:

1. A simple expression language (EL) that can be used to easily access data from a JSP page, which simplifies the authoring of JSP-free applications without the need to use Java scriptlet or Java expressions;

2. A new syntax for directly using JSP technology to define reusable custom behavior that uses. tag and. tagx files, which can be written by developers or web page authors;

3. The 3XML syntax has been substantially improved by adding new standard file extensions (. 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 do we have 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 brackets ([]) operator:

The dot operator is used to access a named property, such as an expression ${customer.name} that represents the scoped variable customer's Name property;
The bracket operator can be used to retrieve named properties, such as 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.

1. Switch directories to C:\Tomcat5.0\webapps\jsp-examples

2. Create a new directory, the name can be arbitrary, such as jsp2-tutorial

3. Switch to Jsp2-tutorial

4. Copy and save the ex1.jsp to the directory

5. Start Tomcat 5 server: Point to Start-> "program"-> "Apache Tomcat 5.0" and click "Apache Tomcat 5.0" to start Tomcat

6. Enter http://localhost:8080/jsp-examples/jsp2-tutorial/ex1.jsp in the browser

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


--------------------------------------------------------------------------------

Note: In this article, all 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" >

</FORM>
<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

Defining and using 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);
}catch (Exception e) {}
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

<%@ taglib prefix= "my"
Uri= "Http://jakarta.apache.org/tomcat/jsp2-example-taglib%>
<HEAD>
<TITLE>Functions</TITLE>
</HEAD>
<BODY>
<P>
<form action= "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 Numbers" >
</FORM>
<P>
The sum is: ${my:add (param["x"],param["Y"])}
</BODY>
</HTML>
To run this example:

1. Copy Compute.java and save to C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\classes\jsp2\examples\el;

2. Compile Compute.java using Javac;

3. Edit the file C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-taglib.tld, add code snippet in code example 4 to the last </in the file Function> label before,</taglib> label;

4. Copy math.jsp and save to C:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial;

5. Open the file in a browser.

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


Figure 3: Working with functions

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 label Extension", which is used in two ways:

1. Java developers can define classes that implement Interface Javax.servlet.jsp.tagext.SimpleTag;

2. Web page writers who do not 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>
<P>
<b>my-Prints</b&gt: <mytag:hello/>
</BODY>
</HTML>
To run this example:

1. Copy Hellotg.java and save to C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\classes\jsp2\examples\simpletag;

2. Compile Hellotag.java using Javac;

3. Add the label descriptor in code example 7 to the </taglib> before the file C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-taglib.tld;

4. Copy the helloworld.jsp and save it to the c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial directory;

5. Open the helloworld.jsp in the 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 example 10:chat.jsp

<%@ taglib prefix= "tags" tagdir= "/web-inf/tags"%>
<HTML>
<HEAD>
&LT;TITLE&GT;JSP 2.0 Examples-hello World Using a Tag file</title>
</HEAD>
<BODY>
<P>
<b>the output of my-tag file Is</b&gt: <tags:greetings/>
</BODY>
</HTML>
To run this example:

1. Copy the label file Greetings.tags and save it in the C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\tags directory;

2. Copy JSP webpage file char.jsp and save in c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial directory;

3. Open the chat.jsp file in a 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 11:display.tag

<%@ attribute name= "COLOR"%>
<%@ attribute name= "bgcolor"%>
<%@ attribute name= "title"%>
<table border= "0" bgcolor= "${color}" >
<TR>
<TD><B>${title}</B></TD>
</TR>
<TR>
&LT;TD bgcolor= "${bgcolor}" >
<jsp:doBody/>
</TD>
</TR>
</TABLE>
Code Example 12 gives a simple JSP page that uses the label above.

code example 12:newsportal.jsp

<%@ taglib prefix= "tags" tagdir= "/web-inf/tags"%>
<HTML>
<HEAD>
<title>another Tag File example</title>
</HEAD>
<BODY>
<table border= "0" >
&LT;TR valign= "Top" >
<TD>
<tags:display color= "#ff0000" bgcolor= "#ffc0c0"
title= "Travel" >
Last French Concorde arrives in ny<br/>
Another Travel headline<br/>
Yet Another Travel headline<br/>
</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<br/>
Nba<br/>
Soccer<br/>
</tags:display>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
To run this example:

1. Copy the file Display.tag and save it under C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\tag;

2. Copy the file newsportal.jsp and save it to c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial;

3. Open the Newsportal file in a 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 Container
JSP Developers Forum
JavaServer Pages Standard Tag Library (JSTL)
Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0)




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.