A sample that shows Java Beans, Servlets and JSP working together

By: Ivan Lim Viewed: 157564 times  Printer Friendly Format    


This tutorial shows the use of Java Beans, JSP and Servlet and how they work together. As an added bonus this tutorial also explains the use of nested properties of Java Beans using EL. The EL provides you with a simple mechanism to access nested properties of a JavaBean. For example, Listing below shows a JavaBean, which has a nested property of type Address

//Person.java
package com.apress.projsp;
public class Person {
private String name;
private int age;
private Address address;
public Person() {
setName("A N Other");
setAge(21);
this.address = new Address();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
}

As you can see, this JavaBean has a property that is in fact another JavaBean—the Address JavaBean (Address.java). Listing below shows the Address JavaBean.

// Address.java
package com.apress.projsp;
import java.util.Collection;
public class Address {
private String line1;
private String town;
private String county;
private String postcode;
private Collection phoneNumbers;
public Address() {
this.line1 = "line1";
this.town = "a town2";
this.county = "a county";
this.postcode = "postcode";
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine1() {
return line1;
}
public void setTown(String town) {
this.town = town;
}
public String getTown() {
return town;
}
public void setCounty(String county) {
this.county = county;
}
public String getCounty() {
return county;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPostcode() {
return postcode;
}
public Collection getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(Collection phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

It’s simple to access these nested properties by using the EL. With the EL, you can chain the various objects and properties in an EL statement. The following JSP snippet shows how you could use chaining to access the line1 property of the address property of the person JavaBean.

${person.address.line1}

The Address JavaBean contains a collection of other JavaBeans as one of its properties. Although you can’t see it in Listing above this collection is a collection of JavaBeans—PhoneNumber JavaBeans. This JavaBean is shown in Listing below.

// PhoneNumber.java
package com.apress.projsp;
public class PhoneNumber {
private String std;
private String number;
public String getNumber() {
return number;
}
public String getStd() {
return std;
}
public void setNumber(String number) {
this.number = number;
}
public void setStd(String std) {
this.std = std;
}
}

The EL also provides a simple mechanism for accessing such collections and the properties of their enclosed JavaBeans. The following JSP snippet would access the first phone number for a person’s address:

${person.address.phoneNumbers[1].number}

As this snippet shows, you can freely mix both dot and bracket notation as needed to access JavaBean properties. 

We can bring this whole discussion together by way of the following example. Listing below shows a JSP page that displays all the details relating to a person and that person’s address. Note how the JSP page uses alternative syntaxes for object property access.

// complexBean.jsp
<html>
<head>
<title>EL and Complex JavaBeans</title>
<style>
body, td {font-family:verdana;font-size:10pt;}
</style>
</head>
<body>
<h2>EL and Complex JavaBeans</h2>
<table border="1">
<tr>
<td>${person.name}</td>
<td>${person.age}</td>
<td>${person["address"].line1}</td>
<td>${person["address"].town}</td>
<td>${person.address.phoneNumbers[0].std}
${person.address.phoneNumbers[0].number}</td>
<td>${person.address.phoneNumbers[1].std}
${person.address.phoneNumbers[1].number}</td>
</tr>
</table>
</body>
</html>

Unlike previous examples where you loaded the JSP page directly, this example uses a simple Java servlet  to set up the information within the JavaBeans. The servlet then adds the object to the request by using the name “person.” The JSP page, as mentioned earlier, searches the various scopes to find the JavaBean with the name used in the EL statement. Listing below, PopulateServlet.java, is the servlet that initializes the various JavaBeans and then uses a RequestDispatcher to forward the request to complexBean.jsp. To compile this class, you’ll need to include a servlet library in the CLASSPATH. If you are using Tomcat 5, you can find the library, servlet-api.jar, in the common\lib directory. If you are using some other web container, check your container documentation for the correct servlet library to include.

// PopulateServlet.java
package com.apress.projsp;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PopulateServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Person p = new Person();
p.setName("Sam Dalton");
p.setAge(26);
Address a = new Address();
a.setLine1("221b Baker Street");
a.setTown("London");
a.setCounty("Greater London");
a.setPostcode("NW1 1AA");
ArrayList al = new ArrayList();
PhoneNumber ph = new PhoneNumber();
ph.setStd("01895");
ph.setStd("678901");
al.add(ph);
ph = new PhoneNumber();
ph.setStd("0208");
ph.setStd("8654789");
al.add(ph);
a.setPhoneNumbers(al);
p.setAddress(a);
req.setAttribute("person", p);
RequestDispatcher rd = req.getRequestDispatcher("complexBean.jsp");
rd.forward(req, res);
}
}

This servlet class should be placed within the WEB-INF\classes\com\apress\projsp folder. You’ll also need to modify the WEB-INF\web.xml file to contain the additional tags in Listing below.

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= ➥
"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>BeanTestServlet</servlet-name>
<servlet-class>com.apress.projsp.PopulateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BeanTestServlet</servlet-name>
<url-pattern>/BeanTest</url-pattern>
</servlet-mapping>
</web-app>

Compile all the Java classes and deploy the files to a web container in the manner described for previous examples. The request for this application is http://localhost:8080/expressionLanguage/BeanTest.  The request is passed to the BeanTestServlet. The servlet creates and initializes the various JavaBeans and forwards the request to complexBean.jsp. 

Figure: shows the web page you would see in your browser.

The expression language can easily handle nested properties of JavaBeans. This example shows how an object or attribute can be created in one part of the web application and accessed from some other part of the application. The JSP page searches the various scopes until it locates the named object.



Most Viewed Articles (in Java Beans )

Latest Articles (in Java Beans)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Hi , I like ur explanation but I need to knw wat i
View Tutorial          By: prabhakara at 2010-09-22 06:28:13

2. excellent work
View Tutorial          By: girijesh at 2010-10-29 15:18:17

3. i think this ist perfectly fine :) if you don't kn
View Tutorial          By: julian at 2011-03-07 05:54:08

4. Hey, this is great. Thanks for the code.
View Tutorial          By: jstrick at 2011-08-27 17:01:20

5. it would be very helpful if you demonstrated how t
View Tutorial          By: newcoder at 2011-10-24 17:40:25

6. hi.....
if we have number of fieldsl ike na

View Tutorial          By: shailesh at 2011-12-15 07:10:34

7. your code error

because i try to ru

View Tutorial          By: Nasser at 2013-01-09 10:33:34

8. So I appreciate this website, however... would it
View Tutorial          By: Christina at 2013-02-06 16:46:12

9. In the absence of frameworks, this is the best exa
View Tutorial          By: Vitalis at 2014-04-29 17:47:16

10. This is the best example for beginners. After read
View Tutorial          By: BB at 2014-05-20 05:24:09

11. Nice tutorial. I would also recommend that the sa
View Tutorial          By: bigT at 2015-02-21 21:50:01

12. I must say you have hi quality content here. Your
View Tutorial          By: 89Petra at 2017-05-14 04:24:34

13. Jaspertip
View Tutorial          By: Jaspertip at 2017-05-22 03:09:02