ZeePedia

JAVA: Expression Language

<< JAVA: Layers and Tiers
JAVA: JavaServer Pages Standard Tag Library (JSTL) >>
img
Web Design & Development ­ CS506
VU
Lesson 42
Expression Language
Sun Microsystems introduced the Servlet API, in the later half of 1997, positioning it as a powerful
alternative for CGI developers who were looking around for an elegant solution that was more efficient and
portable than CGI (Common Gateway Interface) programming. However, it soon became clear that the
Servlet API had its own drawbacks, with developers finding the solution difficult to implement, from the
perspective of code maintainability and extensibility. It is in some ways, this drawback that prompted the
community to explore a solution that would allow embedding Java Code in HTML ­ Java Server Pages
(JSP) emerged as a result of this exploration.
Java as the scripting language in JSP scares many people particularly web page designers which have
enough knowledge to work with HTML and some scripting language, faced lot of difficulties in writing
some simple lines of java code. Can we simplify this problem to ease the life of web designer? Yes, by
using Expression Language (EL).
JavaServer Pages Standard Tag Library (JSTL) 1.0 introduced the concept of the EL but it was constrained
to only the JSTL tags. With JSP 2.0 you can use the EL with template text.
Note: - JSTL will be discussed in the following Handout.
Overview
The Expression Language, not a programming or scripting language, provides a way to simplify
expressions in JSP. It is a simple language that is geared towards looking up objects, their properties and
performing simple operations on them. It is inspired form both the ECMAScript and the XPath expression
language.
JSP Before and After EL
To add in motivational factor so that you start learning EL with renewed zeal and zest, a comparison is
given below that illustrates how EL affects the JSPs.
The following figure depicts the situation of a JSP before EL. We have to declare a variable before using it,
data type must be known in advance and most importantly have to use awkward syntax and many more. All
these problems are highlighted in the following figure:
Contrary to the above figure, have a look on the subsequent figure that gives you a hint how useful EL can
be?
Person Name: $ { p.name }
...
<c:if test = "$ {p.address == param.add }" >
Expression Language Nuggets
We'll discuss the following important pieces of EL. These are:
Syntax of EL
331
img
Web Design & Development ­ CS506
VU
Expressions & identifiers
Arithmetic, logical & relational operators
Automatic type conversion
Access to beans, arrays, lists & maps
Access to set of implicit objects
EL Syntax
The format of writing any EL expression is:
$ { validExpression }
The valid expressions can consist on these individuals or combination of these given below:
Literals
Operators
Variables (object references)
Implicit call to function using property name
EL Literals
The list of literals that can be used as an EL expression and their possible values are given in the tabular
format below:
Literals
Literal Values
Boolean
true or false
Integer
Similar to Java e.g. 243, -9642
Floating Point
Similar to Java e.g. 54.67, 1.83
Any string delimited by single or double quote e.g.
String
"hello" , `hello'
Null
Null
Examples of using EL literals are: . ${ false } <%-- evaluates to false --%> . ${ 8*3 } <%-- evaluates to 24
--%>
EL Operators
The lists of operators that can be used in EL expression are given below:
Type
Operator
Arithmetic
+ -* / (div) % (mod)
Grouping
()
Logical
&&(and) ||( or) !(not)
Relational
== (eq) != (ne) < (lt) > (gt) <= (le) >= (ge)
The empty operator is a prefix operation used to determine if a
Empty
value is null or empty. It returns a Boolean value.
Conditional
?:
332
img
Web Design & Development ­ CS506
VU
Let us look at some examples that use operators as valid expression:
${ (6*5) + 5 } <%-- evaluate to 35 --%>
${ (x >= min) && (x <= max) }
${ empty name }
Returns true if name is
Empty string (""),
Null etc.
EL Identifiers
Identifiers in the expression language represent the names of objects stored in one of the JSP scopes:
page, request, session, or application. These types of objects are referred to scoped variables throughout
this handout.
EL has 11 reserved identifiers, corresponding to 11 implicit objects. All other identifiers assumed to refer
to scoped variables.
EL implicit Objects
The Expression Language defines a set of implicit objects given below in tabular format:
Category
Implicit Object
Operator
The context for the JSP page, used to access the JSP
JSP
pageContext
implicit objects such as request, response, session,
out, servletContext etc.
A Map associating names & values of page scoped
pageScope
attributes
A Map associating names & values of request
requestScope
scoped attributes
Scopes
A Map associating names & values of session
sessionScope
scoped attributes
A Map associating names & values of application
applicationScope
scoped attributes
Maps a request parameter name to a single String
param
parameter value.
Request
Parameters
Maps a request parameter name to an array of
paramValues
values
Maps a request header name to a single header
header
Request
value.
Headers
headerValues
Maps a request header name to an array of value.
A Map storing the cookies accompanying the
Cookies
cookie
request by name
A Map storing the context initialization parameters
Initialization
initParam
Parameters
of the web application by name
Examples of using implicit objects are:
333
img
Web Design & Development ­ CS506
VU
. ${ pageContext.response } -Evaluates to response implicit object of JSP
. ${ param.name } -This expression is equivalent to calling
request.getParameter("name");
${ cookie.name.value } -Returns the value of the first cookie with the given
.
name
-Equivalent to if (cookie.getName().equals("name"){ String val =
cookie.getValue(); }
Example Code: Summation of Two Numbers using EL
This simple example demonstrates you the capabilities of EL. index.jsp is used to collect input for two
numbers and their sum is displayed on result.jsp using EL. Let's first see the code of index.jsp
index.jsp
<html>
<body> Enter two numbers to see their sum
<form action="result.jsp" >
First Number : <input type="text" name="num1" />
<br> Second  Number: <input type="text" name="num2" />
<input type="submit" value="Calculate Sum" />
</form>
</body>
</html>result.jsp
<html>
<body>
<%-- The code to sum two numbers if we used scriptlet
<%
String no1 = request .getParameter("num1");
String no2 = request .getParameter("num2");
int num1 = Integer.parseInt(no1);
int num2 = Integer.parseInt(no2);
%>
Result is: <%= num1 + num2 %>
--%>
<%-- implicit Object param is used to access request
parameters By Using EL summing two numbers --
%> Result is: ${param.num1 + param.num2}
</body> </html>
EL Identifiers (cont.)
We had started our discussion on EL identifiers. Let's find out how these identifiers (variables) can be
stored/retrieved in/from different scopes.
Storing Scoped Variables
By using java code, either in pure servlet or in a scriptlet of JSP, we can store variables in a particular
scope. For example,
. Storing a variable in session scope using Java code
Assume that we have PersonInfo class and we want to store its object pin session scope then we can write
the following lines of code to accomplish that:
334
img
Web Design & Development ­ CS506
VU
HttpSession ses = request.getSession(true);  PersonInfo p = new PersonInfo();
p.setName("ali"); ses.setAttribute("person" , p);
. Storing a variable in request scope using Java code
For the following lines of code, assume that request is of HttpServletRequest type. To store PersonInfo
object p in request scope, we'll write:
PersonInfo p = new PersonInfo(); p.setName("ali");
request.setAttribute("person" , p);
You must be thinking of some another method (with which you are already familiar) to store a variable in a
scope, certainly by using JSP action tags, we learned how to store a variable in any particular scope.
. Storing a variable in request scope using JSP action tag
If we want to store p of type PersonInfo in request scope by using JSP action tags, then we'll
write:
<jsp:useBean id="p" class="PersonInfo" scope="request"/>
Later, you can change the properties of object p by using action tag as well. For example
<jsp:setProperty name="p" property="name" value="ali" />
Retrieving Scoped Variables
You are already very much familiar of retrieving any stored scoped variable by using java code and JSP
action tags. Here, we'll discuss how EL retrieves scoped variables. As already mentioned, identifiers in the
valid expression represent the names of objects stored in one of the JSP scopes: page, request, session and
application.
When the expression language encounters an identifier, it searches for a scoped variable with that name
first
in page scope,
then in request scope,
then in session scope
and finally in application scope
Note: - If no such object is located in four scopes, null is returned.
For example, if we've stored PersonInfo object p in session scope by mean of any mechanism discussed
previously and have written the following EL expression to access the name property of p ${p.name}
Then EL searches for p first in page scope, then in request scope, then in session scope where it found p.
After that it calls p.getName() method. This is also shown in pictorial form below:
335
img
Web Design & Development ­ CS506
VU
336
img
Web Design & Development ­ CS506
VU
$ { "Hello" ${user.firstName} ${user.lastName} }
EL also supports automatic type conversion; as a result primitive can implicitly wrap and unwrap
into/from their corresponding java classes. For example
Most importantly, if object/identifier is null, no NullPointerException would be thrown. For
example. If the expression written is:
${person.name}
Assume that person is null, then no exception would be thrown and the result would also be null.
Using Expression Language
Expression Language can be used in following situations
As attribute values in standard & custom actions. E.g.
<jsp:setProperty id = "person" value = ${....} />
In template text ­ the value of the expression is inserted into the current output. E.g.
<h3> $ { ...... } </h3>
With JSTL (discussed in the next handout)
Example Code: AddressBook using EL
So far, we have shown you implementation of AddressBook example in number of different ways. This
time EL will be incorporated in this example. AddressBook code example consists on searchperson.jsp,
showperson.jsp, ControllerServlet, PersonInfo and PersonDAO classes. Let's look on the code of each of
these components:
PersonInfo.java
The JavaBean used to represent one person record.
package vu;
import java.io.*;
public class PersonInfo implements Serializable{
private String name;
private String address;
private int phoneNum;
// no argument constructor
public PersonInfo() {
name = "";
address = "";
phoneNum = 0;
}
// setters
public void setName(String n){
name = n;
}
public void setAddress(String a){
address = a;
}
public void setPhoneNum(int pNo){
phoneNum = pNo;
}
337
img
Web Design & Development ­ CS506
VU
// getters
public String getName( ){
return name;
}
public String getAddress( ){
return address;
}
public int getPhoneNum( ){
return phoneNum;
}
}
PersonDAO.java
It is used to retrieve/search person records from database.
package vu; import java.util.*; import
java.sql.*; public class PersonDAO{
private Connection con;
// constructor
public PersonDAO() throws ClassNotFoundException , SQLException {
establishConnection();
}
//used to establish connection with database
private void establishConnection() throws
ClassNotFoundException , SQLException
{
// establishing connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conUrl = "jdbc:odbc:PersonDSN";
con = DriverManager.getConnection(conUrl);
}
// used to search person records against name
public ArrayList retrievePersonList(Strin g pName)
throws SQLException {
ArrayList personList = new ArrayList();
String sql = " SELECT * FROM Person WHERE name = ?";
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString( 1, pName);
System.out.println("retrieve person list");
ResultSet rs = pStmt.executeQuery();
String name;
String add;
int pNo;
while ( rs.next() ) {
338
img
Web Design & Development ­ CS506
VU
name = rs.getString("name");
add = rs.getString("address");
pNo = rs.getInt("phoneNumber");
// creating a PersonInfo object
PersonInfo personBean = new PersonInfo();
personBean.setName(name); personBean.setAddress(add);
personBean.setPhoneNum(pNo);
// adding a bean to arraylist
personList.add(personBean);
} // end while
return personList;
} // end retrievePersonList
//overriding finalize method to release resources
public void finalize( ) {
try{
if(con != null){
con.close();
}
}catch(SQLException sex){
System.out.println(sex);
}
} // end finalize
} // end class
searchperson.jsp
This JSP is used to gather person's name from the user and submits this data to the ControllerServlet.
<html>
<body>
<center>
<h2> Address Book </h2>
<h3> Search Person</h3>
<FORM name ="search" action="controllerservlet" />
<TABLE BORDER="1" >
<TR>
<TD> <h4 >Name</h4> </TD>
<TD> <input type="text" name="name" /> </TD>
</TR>
<TR>  <TD COLSPAN="2" ALIGN="CENTER"">
<input type="submit" value="search" /> <input type="reset"
value="clear" />
</TD>
</TR>
</TABLE>
</FORM>
</center>
</body>
</html>
ControllerServlet.java
The Controller Servlet receives request from searchperson.jsp and after fetching search results from
database, forwards the request to showperson.jsp.
package controller;
339
img
Web Design & Development ­ CS506
VU
import vu.*;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ControllerServlet extends HttpServlet {
} // end processRequest()
// This method only calls processRequest()
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
// This method only calls processRequest()
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
// defined below
searchPerson(request, response);
} // end ControllerServlet
protected void searchPerson(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
try {
// creating PersonDAO object
PersonDAO pDAO = new PersonDAO();
// retrieving request parameter "name" entered on showperson.jsp
String pName = request.getParameter("name");
// calling DAO method to retrieve personlist from database // against the name entered
by the user
ArrayList personList = pDAO.retrievePersonList(pName);
// storing personlist in request scope, later it is retrieved // back on showperson.jsp
request.setAttribute("plist", personList);
// forwarding request to showperson, so it renders personlist
340
img
Web Design & Development ­ CS506
VU
RequestDispatcher rd =  request.getRequestDispatcher("showperson.jsp");
rd.forward(request, response);
}catch (Exception ex) {
System.out.println("Exception is" + ex);
}
} // end searchPerson
showperson.jsp
This page is used to display the search results. To do so, it reclaims the stored ArrayList (personList) from
the request scope. Furthermore, this page also uses the Expression Language to display records.
<%-- importing required packages--%>
<%@page import="java.util.*" %>
<%@page import="vu.*" %>
<html>
<body>
<center>
<h2> Address Book </h2>
<h3> Following results meet your search criteria</h3>
<TABLE BORDER="1" >
<TR>
<TH>Name</TH>
<TH>Address</TH>
<TH>PhoneNum</TH>
</TR>
<%-- start of scriptlet --%>
<%
// retrieving ArrayList from request scope
ArrayList personList =(ArrayList)request.getAttribute("plist");
PersonInfo person = null;
for(int i=0; i<personList.size(); i++) {
person = (PersonInfo)personList.get(i);
// storing PersonInfo object in request scope /* As mentioned, an object must be
stored in some scope to work with Expression Language*/
request.setAttribute("p", person);
%>
<%-- end of scriptlet --%>
<TR>
<%-- accessing properties of stored PersonInfo object with name "p" using EL --%>
<TD> ${ p.name } </TD> <TD> ${ p.address} </TD>
<TD> ${ p.phoneNum} </TD>
<%-- The following expressions are now replaced by EL statements written above--%>
<%--<%= person.getName()%> --%> <%--<%=
person.getAddress()%> --%> <%--<%=
341
img
Web Design & Development ­ CS506
VU
person.getPhoneNum()%> --%>
</TR>
<%
} // end for
%>
</TABLE >
</center>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name> ControllerServlet </servlet-name>
<servlet-class> controller.ControllerServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> ControllerServlet </servlet-name>
<url-pattern> /controllerservlet </url-pattern>
</servlet-mapping>
</web-app>
References:
. Java A Lab Course by Umair Javed.
. Expression Language Tutorial by Sun
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html
The JSTL Expression Language by David M. Geary
http://www.informit.com/articles/article.asp?p=30946&rl=1
342