Developing Web applications with JSP 2.0 1

Source: Internet
Author: User
Tags empty expression functions new features string version variable apache tomcat
js|web| Program


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.



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 JSP pages, 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 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 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 Name property of the scoped variable customer;
    • 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 of ${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, an 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 parameter 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 : An implied object in an 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



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 objects can be used to read data that fills the 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 ']}" >
                    
<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);
        
            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 the file C:\Tomcat5.0\webapps\jsp-examples\WEB-INF\jsp2\jsp2-example-taglib.tld to add the code snippet from code example 4 to the last </function in the file > label after,</taglib> label;
Copy the math.jsp and save it to the c:\Tomcat5.0\webapps\jsp-examples\jsp2-tutorial;
Open the file in a browser.

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.