Building Scriptless JSP Applications with JSP2.0 Expression Language

版权申明:你可以任意转载此文,但必须保持文章的完整性,并且标明此文的出处,谢谢!
作者序:这是我4年前练手写的一篇英文技术文章,几乎没有公开过,出来献丑了。

Building Scriptless JSP Applications with JSP2.0 Expression Language

Level: Intermediate

Summary:

The Primary feature of JSP technology version 2.0 is its support for an expression languag, the expression language can now be used in JSP page instead of scriptlet expressions. In this article, first introduce some important concept about JSP2.0 Expression Language (EL), then demonstrate how to use EL to build a scriptless sample JSP application.
Expression Language Introduction

The JavaServer Pages Standard Tag Library (JSTL) expression language is now integrated into JSP technology and has been upgraded to support functions. The expression language can now be used in JSP page instead of scriptlet expressions. By use of Expression Language, Web designers produce scriptless JSP pages that don’t contain any Java code.

An expression language makes it possible to easily access application data stored in JavaBeans components or JSP implicit objects.

For example, in JSP1.2, you can use the following code to access a JavaBeans component:

Listing 1. access JavaBeans components with JSP1.2 or earlier

<jsp:useBean id=”user” class=”com.hellking.UserBean” scope=”page”/>

<%

out.println(user);

out.println(user.getUserName());

%>

In JSP2.0, you can access the property and variable by using EL through the following way:

Listing 2: access JavaBeans components by EL with JSP2.0

<jsp:useBean id=”user” class=”com.hellking.UserBean” scope=”page”/>

${user}<br>

${user.userName}

In listing2, we use “${user}” to access the JavaBean component, and use “${user.userName}” to access a nested property, and we can use “${user.userName.firstName}” to access more complex nested property.

The JSP expression evaluator is responsible for handling EL expressions, which may include literals and are enclosed by the ${ } characters. For example:

<c:if test=”${user.age < 30}” >

</c:if>

We can use the Expression Language to set tag’s property, for example:

Listing 3 set tag’s property

<c:set target=”${user}” property=”userName”>sdf234sdfd</c:set>

<c:set var=”foo” value=”the user is ${user.userName} and the password is ${user.password}”/>

The JSP container evaluates a variable that appears in an expression by looking up its value according to the behavior of PageContext.findAttribute(String). For example, when evaluating the expression ${user}, the container will look for user in the page, request, session, and application scopes and will return its value. If both the page and session has the attribute “user”, it will return the attribute of the page. If “user” is not found in any scope , null is returned.

The JSP expression language defines a set of implicit objects (Don’t confuse these with the JSP implicit objects), with the implicit objects, you can access variable in a very easy way. For example, in JSP1.2 or earlier, you use following code to access implicit objects and their values:

Listing 4 access implicit objects with JSP1.2 or earlier

<%

session.setAttribute(“user”,”hellking”);

out.println(session.getAttribute(“user”));

out.println(request.getParameter(“password”));

%>

And you may use the following code in JSP2.0:

Listing 5 access implicit objects with JSP2.0

<c:set var=”user” value=”hellking” scope=”session”/> <!–set a property in session –>

${sessionScope.user}<br> <!– get a property in session –>

${param.password}<br> <!– equal to request.getParameter(“password”) –>

You can see, Expression language provide a map between JSP implicit objects and their method(property).

You can access the JSP page context objects, page/request/session/application attributes (also known as JSP variables), JavaBean properties, collection elements, request parameters, initialization parameters, cookies, and HTTP headers.

With JSP 1.2, the expression language is available only to JSTL-based applications and tag libraries. JSP 2.0 makes the EL available to all JSP applications and all tag libraries (including the old taglibs designed for JSP 1.x). JSP 2.0 also simplifies tag library development, as you’ll see later in this article.

For more information about implicit objects map, see The Java Web Services Tutorial, http://java.sun.com/webservices/docs/1.2/tutorial/doc/JSPIntro7.html#wp71043.

NOTE:

JSP2.0 Expression Language is somewhat different from JSLT1.0 Expression Language. For Example, in JSTL1.0, use the following to output the variable’s value to client:

<c:out value=”${test}”/>

and in JSP2.0 EL, just use the following code:

${test}

Set up envirmonent

1. Download Apache Tomcat 5.0 and setup it, see Resource.

2. Create a web application in %Tomcat_Home%\webapps directory, the web application name is “el”.

3. In the “el” application directory, create a sub directory WEB-INF; and then in WEB-INF directory, create a web application descriptor file: web.xml. Copy the following descriptor to web.xml file.

Listing 6 new web.xml descriptor

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<web-app xmlns=”http://java.sun.com/xml/ns/j2ee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd”

version=”2.4″>

<display-name>jstl_el</display-name>

<description>

a demo EL application

</description>

<welcome-file-list>

<welcome-file>viewUser.jsp</welcome-file>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

</web-app>

NOTE: JSP2.0 descriptor is defined by w3c schema, and JSP1.x descriptor is defined by DTD. So I recommend you use the new descriptor, or if you use old descriptor, you JSP file may include:

<%@ page isELIgnored =”false” %>

4. In the WEB-INF directory, create a sub directory, the name is lib. Copy jstl.jar and standard.jar form %Tomcat_Home%\webapps\jsp-examples\WEB-INF\lib to the lib directory.

5. Test configuration. In the el directory, create a JSP whose name is el.jsp, and then copy the following code to the el.jsp file.

Listing 7 Test EL configuration

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>

<html>

<head>

<title>test jstl configuration</title>

</head>

<body bgcolor=”#FFFFFF”>

<hr>

<c:set var=”test” value=”test_Value”/>

<hr>

the value of test is:

${test}</body>

</html>

Startup Tomcat, view the following URL from the browser:

http://127.0.0.1:8080/el/el.jsp

If the output is:

the value of test is: test_Value

Congratulation! the first EL application is run!

Build a Sample application

Now we discuss how to build a JSP application with JSP2.0 EL.

The application is a simple user register and manage program. The following is user register interface.

Figure 1 user register interface(userRegister.jsp)

And you can delete registered user in the following interface.

Figure2 view and delete registered user(viewUser.jsp)

In the database, use the following script to create a table:

use test;

create table UserInfo(id varchar(20) not null,userName varchar(30),password varchar(20),age int,constraint pk_UserInfo primary key (id));

And then you may copy the class file of the database server’s JDBC driver to the %Tomcat_Home%\common\lib directory.
jstl.inc

jstl.inc file is a public file included by other JSP.

Listing 8 jstl.inc

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page language="java" errorPage="error.jsp" %>

<sql:setDataSource

var="jspdev"

driver="org.gjt.mm.mysql.Driver"

url="jdbc:mysql:///test"

user="root"

password=""

scope="session"

/>

You may modify the content of the <sql:setDataSource> tag according to the database settings.

NOTE

The uri of JSP2.0 tag is

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

but by default, the uri of JSTL1.0 tag is:

<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

Don’t be confused.

userRegister.jsp

userRegister.jsp contain a HTML form, which used to submit user’s registration information. If the submitted registration information is invaluable, the error message and original parameter’s value is returned.

Listing 9 userRegister.jsp

<%@ include file="jstl.inc"%>

note:${param.message}<br></font>

User Register:<br><hr>

:::please input your register info and submit:::

<form method="get" action="register_do.jsp" name="user" onsubmit="return validate(user.age)">

<table align="center" bgcolor="#008800" border="0" cellspacing="2" cellpadding="5">

<tr bgcolor="#cccccc"><td align=right>login id:<input name="id" type="text" value="${param.id}" ></td></tr>

<tr bgcolor="#cccccc"><td align=right>true name:<input name="userName" type="text" value="${param.userName}"></td></tr>

<tr bgcolor="#cccccc"><td align=right>password:<input name="password" type="password" value="${param.password}"></td></tr>

<tr bgcolor="#cccccc"><td align=right>your age:<input name="age" type="text" value="${param.age}" ></td></tr>

<tr bgcolor="#cccccc"><td ><input type=submit value="submit"></td></tr>

</table>

</form>

<c:import url="tail.html"/>


register_do.jsp

In the register_do.jsp, first it validate the form’s parameter, if the parameter is invaluable, redirect back to the registration page; if the parameter is validly, execute the <sql:update> tag and save the data to database.

Listing 10 register_do.jsp

<%@ include file="jstl.inc"%>

<c:choose>

<c:when test="${empty param.id or empty param.userName or empty param.password}">

<c:set var="nextPage" value="userRegister.jsp"/>

<c:set var="message" value="column id. name .password can't be null!" scope="page"/>

</c:when>

<c:when test="${empty param.age or param.age gt 100 or param.age lt 0}">

<c:set var="nextPage" value="userRegister.jsp"/>

<c:set var="message"

value="column age can not be null, and age must be a integer between 0 and 100 !'"/>

</c:when>

<c:otherwise>

<sql:update var="user"

dataSource="${jspdev}"

sql="insert into UserInfo

values('${param.id}','${param.userName}','${param.password}','${param.age}')"/>

<c:set var="nextPage" value="viewUser.jsp"/>

<c:set var="message" value="${param.id}"/>

</c:otherwise>

</c:choose>

<c:redirect url="${nextPage}">

<c:param name="message" value="${message}"/>

<c:param name="userName" value="${param.userName}"/>

<c:param name="id" value="${param.id}"/>

<c:param name="age" value="${param.age}"/>

<c:param name="password" value="${param.password}"/>

</c:redirect>

See the following EL:

${empty param.id or empty param.userName or empty param.password}

is equal to:

<%

if(request.getParameter("id").equals(null)||request.getParameter("id").equals(null)||request.getParameter("id").equals(null))

%>

“empty” and “or” are EL operator, “empty param.id” means no request parameter “id” or the request parameter “id” has a null value. The following EL:

${empty param.age or param.age gt 100 or param.age lt 0}

is equal to:

<%

if(request.getParameter("age").equals(null)||Integer.parseInt(request.getParameter("age"))<0 ||Integer.parseInt(request.getParameter("age"))>100)

%>

“gt” and “lt” is EL operator, ”gt” means the mathematic operator ”>”, ”lt” means the mathematic operator ”<”.
viewUser.jsp

viewUser.jsp is used to view the registered user’s information.

Listing 11 viewUser.jsp

<%@ include file="jstl.inc"%>

<sql:query var="query" dataSource="${jspdev}">

select * from userinfo

</sql:query>

<br><br><br>

:::::::::the follow is all user in the system:::::::::<br>

<table align="center" bgcolor="#008800" border="0" cellspacing="2" cellpadding="5">

<tr bgcolor="#cccccc">

<td>id</td>

<td>name</td>

<td>age</td>

<td>delete</td>

</tr>

<c:forEach var="row" items="${query.rows}">

<tr bgcolor="#FFFF88">

<td> ${row.id}</td>

<td> ${row.userName}</td>

<td> ${row.age}</td>

<td><a href="deleteUser_do.jsp?id=${row.id}"/>delete</a></td>

</tr>

</c:forEach>



Unlike the JDBC programme, you can use ${row.id} EL to access the ResultSet Object. As you can see, ${row.id} is equal to the following scriptlet:

<% out.println(resultSet.getString(“id”);%>

Because a JSP function is used in deleteUser_do.jsp, so let’s see something about JSP function.
Use function in JSP2.0

JSP2.0 EL lets you call a Java class’s public static method using the following syntax:

${prefix:methodName(param1, param2, …)}

The JSP function must be declared in a tag library descriptor (TLD):

<function>

<name>methodName</name>

<function-class>className</function-class>

<function-signature>

returnType methodName(param1Type, param2Type, …)

</function-signature>

</function>

The Java class doesn’t have to implement any special interface. The only requirement is to make the Java method public and static.

The following is the function’s class used in the demo application.

Listing 12 StringUtil.java

package com.hellking;

public class StringUtil

{

public static String trim(String s1)

{

return s1.trim();

}

}

As mentioned earlier, the JSP function must be declared in a tag library descriptor. The functions.tld file defines some version number, the library’s URI, the function’s name, the name of the class containing the static method, and the method’s signature. The URI doesn’t have to point to an existing Web resource, but it must be unique. You may not use the same URI for two different tag libraries.

Here is the functions.tld file’s content:

Listing 13 functions.tld

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>

<taglib xmlns=”http://java.sun.com/xml/ns/j2ee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd”

version=”2.0″>

<tlib-version>1.0</tlib-version>

<jsp-version>1.2</jsp-version>

<short-name>function</short-name>

<uri>http://hellking.com/function</uri>

<display-name>JSTL sql RT</display-name>

<description>my function</description>

<function>

<name>trim</name>

<function-class>com.hellking.StringUtil</function-class>

<function-signature>java.lang.String trim(java.lang.String)</function-signature>

</function>

</taglib>

The functions.tld file must be placed into the Web application’s /WEB-INF directory. The same directory also contains the web.xml application descriptor, which declares the library within a <taglib> element. Add the following descriptor to the web.xml descriptor file.

Listing 14

<taglib>

<taglib-uri>http://hellking.com/function</taglib-uri>

<taglib-location>/WEB-INF/functions.tld</taglib-location>

</taglib>

Now let’s see the usage of the JSP function.

Listing 11 deleteUser_do.jsp

<%@ taglib prefix=”myfun” uri=”http://hellking.com/function”%>

<%@ include file=”jstl.inc”%>

<sql:update var=”user”

dataSource=”${jspdev}”

sql=”delete from UserInfo where id=’${myfun:trim(param.id)}’”/>

<c:redirect url=”viewUser.jsp”/>

Before calling the trim () function, the deleteUser_do.jsp page must specify the function’s prefix and the library’s Uniform Resource Identifier (URI):

<%@ taglib prefix=”myfun” uri=”http://hellking.com/function”%>

And then we can use the function as the following way:

${myfun:trim(param.id)}

“myfun” is the prefix of the tag, “trim()” is name of the function defined in the tag library’s descriptor.

Resource:

Down the sample code here .

Download Tomcat 5 to run the JSP 2.0 examples:

http://jakarta.apache.org/builds/jakarta-tomcat/release

The Java Web Services Tutorial:

http://java.sun.com/webservices/docs/1.2/tutorial/doc/index.html

The JSP homepage: http://java.sun.com/products/jsp

The JSTL homepage:

http://java.sun.com/products/jsp/jstl

The JSP 2.0 specification:

http://jcp.org/aboutJava/communityprocess/first/jsr152/index2.html

The J2EE 1.4 Tutorial has a few chapters about JSP 2.0:

http://java.sun.com/j2ee/1.4/docs/tutorial

Call JavaBean methods from JSP 2.0 pages:

http://www.javaworld.com/javaworld/jw-05-2003/jw-0523-calltag.html

Apache Tomcat 5 supports JSP 2.0:

http://jakarta.apache.org/tomcat

A JSTL primer, Part 1: The expression language:

http://www-106.ibm.com/developerworks/java/library/j-jstl0211.html

About the author

Ya qiang Chen, a professional J2EE programmer, he has three years J2EE experience. He is interested in J2EE and Web Services technology. Except successful J2EE project, he also has written some books and articles about J2EE/Web Services program. Contact Ya qiang Chen at cyqcims@mail.tsinghua.edu.cn.

Leave a Reply

You must be logged in to post a comment.