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

By: Ivan Lim Emailed: 1674 times Printed: 2158 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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.


Java Beans Home | All Java Beans Tutorials | Latest Java Beans Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(8)


1. View Comment

Hi , I like ur explanation but I need to knw wat is server side programming functions , ATG , Spring ,servlets,javabeans,
jsp pages , EL.
simple languages would be better to understand with good example.


View Tutorial          By: prabhakara at 2010-09-22 06:28:13
2. View Comment

i think this ist perfectly fine :) if you don't know any keywords you can look them up @ google ;)

View Tutorial          By: julian at 2011-03-07 05:54:08
3. View Comment

it would be very helpful if you demonstrated how to construct the new person (sam dalton) through input collection from a jsp page.

View Tutorial          By: newcoder at 2011-10-24 17:40:25
4. View Comment

hi.....
if we have number of fieldsl ike name,age,phone,email,mob,resume,resumetitle...etc then is it good to declare in class..or better to create DTO.for such fields...using connectivity with database......friends suggest me way...plz..


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

your code error

because i try to run by http://localhost:8081/BeanTest

and i get to page not found HTTP 404


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

So I appreciate this website, however... would it kill you guys to tab?

View Tutorial          By: Christina at 2013-02-06 16:46:12
7. View Comment

In the absence of frameworks, this is the best example of retrieving composite attributes from a bean, I have come across. Thanks for the information

View Tutorial          By: Vitalis at 2014-04-29 17:47:16
8. View Comment

This is the best example for beginners. After read this I'm very clear about the MVC concept. Thank you

View Tutorial          By: BB at 2014-05-20 05:24:09

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ivan Lim
Requesting a Signed Certificate from a Certification Authority example using keytool in Java
The if-then Statement in Java
SELECT Statements
The BodyTag Interface in JSP
Handling Duplicate Form Submissions in Struts
Standard Input and Output in C
A sample that shows Java Beans, Servlets and JSP working together
Recursion in C
Using Multibox in Struts
switch in C
Word Counting sample program in C
Java Bean Scopes in JSF
Using cout.width() in C++
Types of configurations in J2ME
How to get the CLDC and MIDP version from a J2ME program

More Tutorials in Java Beans
Creating a JavaBean to Connect with Google API
Spring Vs EJB ( A feature comparison)
What is EJB server and what are EJB Components?
JavaBeans Basic Concepts
JavaBeans vs. Custom Tags
Java Beans and the Expression Language
A sample that shows Java Beans, Servlets and JSP working together
Advantages of Java Beans
Design Patterns for Properties in a Java Bean
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
ADVANTAGES OF EJB
Steps to develop EJB Environment
EJB is a server side component:
Entity Bean
History Of Java

More Latest News
Most Viewed Articles (in Java Beans )
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
A sample that shows Java Beans, Servlets and JSP working together
Advantages of Java Beans
JavaBeans Basic Concepts
What is EJB server and what are EJB Components?
Reusable component
ADVANTAGES OF EJB
Java Beans and the Expression Language
Spring Vs EJB ( A feature comparison)
Design Patterns for Properties in a Java Bean
JavaBeans vs. Custom Tags
Steps to develop EJB Environment
Entity Bean
Creating a JavaBean to Connect with Google API
EJB is a server side component:
Most Emailed Articles (in Java Beans)
Reusable component
History Of Java
EJB is a server side component:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Steps to develop EJB Environment
Entity Bean
Advantages of Java Beans
Java Beans and the Expression Language
JavaBeans vs. Custom Tags
ADVANTAGES OF EJB
Design Patterns for Properties in a Java Bean
What is EJB server and what are EJB Components?
Spring Vs EJB ( A feature comparison)
A sample that shows Java Beans, Servlets and JSP working together
JavaBeans Basic Concepts