You are on page 1of 17

JavaBeans

JavaBeans
JavaBeans is a software component architecture that extends the power of
the Java language by enabling well-formed objects to be manipulated
visually at design time in a pure Java builder tool, such as NetBeans and
Eclipse.
In general, a JavaBean is a class but it must following three rules:
1.
2.
3.

It must have a default constructor


It can't declare any public instane variable. You should declare instance variables
as private or protected.
It mist cotain get and set methods for all of the properties that need to be
accessed by JSPs.

Note when coding a getter for return a Boolean value, you should use is
method instead of get method. For example, is Gradudated.
When coding the get, set and is methods, you must follow the capitalization
conventions. So each method name must start with a lowercase letter and
each property name must start with an uppercase letter. For exaple,
setFirstName().
Also, it is commeon for a JavaBean to implement the Serializable interface,
though it is not required. So another class can use the set, get, and is
method to read and write an object's instance variables to and form a
persistent data source.
It is common to use JavaBeans to dedfine the business object. And these
JavaBeans are clalled Invisiable JavaBeans. However, JavaBeans can be used
to define buttons and other user-interfaces controls.

The User Bean class


package business;
import java.io.Serializable;
public class User implements Serializable {
private String firstName;
private String lastName;
private String emailAddress;
public User() {
firstName = "";
lastName = "";
emailAddress = "";
}

public User(String firstName, String lastName, String emailAddress) {


this.firstName = firstName;
this.lastName = lastName;
this.emailAddress = emailAddress;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}

Standard JSP tags


JSP tags for using JavaBeans make it easier for non-programmers to use
beans because they look more like HTML tags and don't require the use of
Java code.
Example
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"
value="<jsp:getProperty name="user" property="firstName"/>"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value="<jsp:getProperty name="user" property="lastName"/>"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value="<jsp:getProperty name="user" property="emailAddress"/>"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit" value="Submit"></td>
</tr>
</table>

The JSP without using jsp tags to access the


User bean
<%@page import="business.User" %>
<%
User user = (User) session.getAttribute("user");
if (user == null) {
user = new User();
}
%>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName" value="<%= user.getFirstName() %>"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName" value="<%= user.getLastName() %>"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress" value="<%= user.getEmailAddress() %>"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit" value="Submit"></td>
</tr>
</table>

JSP Expression Language


The JSP Expression language (EL) provides a compact
syntax that lets you get data from JavaBeans, maps,
arrays, and lists that have been stored as attributes of a
web application.
Advantages of EL

has a more elegant and compact syntax than standard JSP tags.
lets you access nested properties.
lets you access collections such as maps, arrays, and lists.
does a better job of handling null values
provides more functionality.

Disadvantages of EL
doesn't create a JavaBean if it doesn't already exist.
doesn't provide a way to set properties.

Comparison of EL and JSP tags


Using EL to access a User object
that stored in Session

Using JSP tags to access a User


object that stored in Session

<table cellspacing="5" border="0">


<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"
value="${user.firstName}"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value="${user.lastName}"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value="${user.emailAddress}"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit"
value="Submit"></td>
</tr>
</table>

<jsp:useBean id="user" scope="session"


class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text"
name="firstName"
value="<jsp:getProperty name="user"
property="firstName"/>"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text"
name="lastName"
value="<jsp:getProperty name="user"
property="lastName"/>"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text"
name="emailAddress" value="<jsp:getProperty
name="user" property="emailAddress"/>"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit"
value="Submit"></td>
</tr>
</table>

Working with EL
Typically before you can use EL to access a javaBean object, a
Servlet needs to use setAttribute method to store objects in
either request or session scope (i.e. HttpServletRequest and
HttpSession respectively). Or even you can store the object
within page scope using implicit PageContext.
In JSP, you use the dot operator, the code to the left of the
operator must specify a JavaBean or a map, and the code to the
right of the operator must specify a JavaBean property or a map
key.
Syntax:
${attribute}

When you use this syntax, EL looks up the attribute starting with
the smallest scope (page scope) and moving towards the largest
scope (application scope).
Search sequence
1.
2.
3.
4.

Page scope (in impliciit PageContext object)


Request scope (in the HttpServletRequest object)
Sessionage scope (in the HttpSession object)
Application scope (in the ServletContext object)

Examples of EL
Example of accessing an attribute in the request object
Servlet code
Date currentDate = new Date();
request.setAttribute("currentDate", currentDate);

JSP code
<p>The current date is ${currentDate}</p>

Example of accessing a property of an attribute


Servlet code
User user = new User(firstName, lastName, emailAddress);
session.setAttribute("user", user);

JSP code
<p>Hello ${user.firstName}</p>

Using EL to specify scope


If there is a naming conflict, you can use the implicit EL objects to specify scope.

pageScope for page scope


requestScope for request scope
sessionScope for session scope
applicationScope for application score

Syntax:
${scope.attribute}

All of the implicit EL objects for specifying scope are maps. As a result, you can use the
dot operator to specify a key when you want to return the object for that key.
Example of specifying request scope
Servlet code
Date currentDate = new Date();
request.setAttribute("currentDate", currentDate);

JSP code
<p>The current date is ${requestScope.currentDate}</p>

Example of specifying session scope


Servlet code
User user = new User(firstName, lastName, emailAddress);
session.setAttribute("user", user);

JSP code
<p>Hello ${sessionScope.user.firstName}</p>

Using [] operator to with arrays and lists


The [] operator is used to work with arrays and lists. However, it can also be used with JavaBeans and
maps.
Syntax:

${attribute["propertyKeyOrIndex"]}

Example of using [] operator with a JavaBean property

Servlet
User user = new User(Peter, Lee, peter@yahoo.com);
session.setAttribute("user", user);

JSP
<p>Hello ${user[firstName]}</p>

Example of using [] operator with an array

Servlet
String[] grades= {A, B, C};
ServletContext application = this.getServletContext();
application.setAttribute(grades, grades);

JSP
<p>The best grade is ${grades[0]}<br>
The second best grade is ${grades[1]} </p>

Example of using [] operator with a list

Servlet
ArrayList<User> users = UserRepository.getUsers(path);
season.setAttribute(users, users);

JSP
<p>The first users address is ${users[0].emailAddress}<br>
The second users address is ${users[1].emailAddres} </p>

Using the [] operator to access nested


properties

If a JavaBean has a property that returns another JavaBean,


you can use the dot operator to access nexted properties.
Syntax:
${attribute.property1.property2} or
${attribute["property1"].property2}

Example of accessing a nested property


Servlet
Book b = new Book();
b.setIsbn(1234567890);
OrderItem orderItem = new OrderItem(b, 5);
session.setAttribute(item, orderItem);

JSP
<p>Book ISBN: ${item.book.isbn}</p>
Or
<p>Book ISBN: ${item[book].isbn}</p>

Using the [] operator to access attributes


If the expression within the [] operator isn't enclosed within quotes, EL
evaluates the expression. FIrst, EL checks if the expression is an attribute.
Thenm it attempts to evaluate the expression.
Syntax:
${attribute[attribute].property}
${attribute[attribute[index]].property}

Example of using an attribute with the [] operator


Servlet

TreeMap<String, User> map = UserRepository.getUsersMap(path);


session.setAttribute(usersMap, map);
String emailAddress = request.getParameter(emailAddress);
session.setAttribute(emailAddress , emailAddress);

JSP

<p>First name: ${userMap[emailAddress].firstName}</p>

Another Example of using an attribute with the [] operator


Servlet

TreeMap<String, User> map = UserRepository.getUsersMap(path);


session.setAttribute(usersMap, map);
String[] emailAddresses = {"peter@yahoo.com", lily@yahoo.com, nancy@gmail.com};
session.setAttribute("emailAddresses", emailAddresses);

JSP

<p>First name: ${userMap[emailAddresses[0]].firstName}</p>

Implicit EL Objects
They are built-in objects that allow you to perform common tasks in a JSP.
All of the implicit objects are maps, except for the pageContext object which is a JavaBean.

Implicit object

Description

param

A map that returns a value for the specified request


parameter name.

paramValues

A map that returns an array of values for the specified


request parameter name.

header

A map that returns the value for the specified HTTP


request parameter name.

headerValues

A map that returns an array of values for the specified http


request header.

cookie

A map that returns the Cookie obect for the specified


cookie.

initParam

A map that returns the value for the specified parameter


name in the context-param element of the web.xml file.

pageCount

A reference to the implicit pageContext object thats


available from any JSP.

Examples of Implicit EL Objects

To get parameter values from the request


HTML code

<form action="joinToContactList", method="post">


<p>First Name: <input type="text" name="firstName">></p>
<p>Email address 1: <input type="text" name="emailAddress"></p>
<p>Email address 2: <input type="text" name="emailAddress"></p>
</form>

JSP code

<p>First Name: ${param.firstName}<br>


Email address 1: ${paramValues.emailAddress[0]}<br>
Email address 2: ${paramValues.emailAddress[1]}<br>
</p>

To get an HTTP header


JSP code

<p>Browser MIME types: ${header.accept}<br>


Browser compression types: ${header["accept-encoding"]}
</p>

The header returned from the header object

Browser MIME types:


text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Browser compression types: gzip, deflate

Examples
of
Implicit
EL
Objects
To work with cookies
Servlet code

Cookie c = new Cookie("emailCookie", emailAddress);


c.setMaxAge(60*60); //set its age to 1 hour
c.setPath("/"); //allow the entire application to access it
response.addCookie(c);

JSP code
<p>The email cookie: ${cookie.emailCookie.value}</p>

To get a context initialization parameter


Xml code in web.xml

<context-param>
<param-name>addmissionsEmail</param-name>
<param-value>monica@npu.edu</param-value>
</context-param>

JSP code

<p>The context init param: ${initParam.addmissionsEmail}</p>

To use the pageContext object


JSP code

<p>HTTP request method: ${pageContext.request.method}<br>


HTTP response type: ${pageContext.response.contentType}<br>
HTTP session ID: ${pageContext.session.id}<br>
HTTP servletContext path: ${pageContext.servletContext.contextPath}<br>
</p>

The output displayed in the web browser

HTTP request method: POST


HTTP response type: text/html;charset=UTF-8
HTTP session ID: FF6672E1AB76403C8C20BB0C01AF9B85
HTTP servletContext path: /ContactList_JavaBeans_EL

Other EL Operators

Besides the dot operator and {} operator, there are other


operators available from EL. And you can use them to perform
calculations and comparisons.
Operator

Alternative

Operator

Alternative

==

eq

&&

and

!=

ne

||

or

<

lt

not

Operator

Alternative

div

>

gt

mod

<=

le

>=

ge

Example:
<p>Operator test: ${1 + 1}</p>

Operator

Alternative

empty x

Returns true if the value of x is null or equal to an empty


string

X?Y:Z

If X evaluates to true, returns Y. Otherwise return Z

You might also like