JavaBeans are Java classes that can be easily reused and composed together into an application. Any Java class that follows certain design conventions can be a JavaBeans component. JavaBeans has properties of the class and public methods to get and set properties. Within a JSP page, you can create and initialize beans and get and set the values of their properties. JavaBeans can contain business logic or data base access logic

A JavaBeans component property can be

  • Read/write, read-only, or write-only
  • Simple, which means it contains a single value, or indexed, which means it represents an array of values

There is no requirement that a property be implemented by an instance variable; the property must simply be accessible using public methods that conform to certain conventions:

  • For each readable property, the bean must have a method of the form
    • PropertyClass getProperty() { … }
  • For each writable property, the bean must have a method of the form
    • setProperty(PropertyClass pc) { … }

In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters.   If there are no other constructors, no arg constructor is automatically generated.

What are JavaBeans?

Java classes that follow certain conventions

  • Must have a zero-argument (empty) constructor
    • You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors
  • Should have no public instance variables (fields)‏
    • I hope you already follow this practice and use accessor methods instead of allowing direct access to fields
  • Persistent values should be accessed through methods called getXxx and setXxx
    • If class has method getTitle that returns a String, class is said to have a String property named title
    • Boolean properties use isXxx instead of getXxx
  • For more on beans, see

Why to use accessor methods?

To be a bean, you CANNOT have public fields. So, you should replace all for your public fields with accessor methods. For example,

public double speed;

should be replaced with:

private double speed;
public double getSpeed() {
public void setSpeed(double newSpeed) {
  speed = newSpeed;
You can put constraints on values

If users of your class accessed the fields directly, then they would each be responsible for checking constraints.

public void setSpeed(double newSpeed) {
  if (newSpeed < 0) {
    newSpeed = Math.abs(newSpeed);
  speed = newSpeed;
You can change your internal representation without changing interface
// Now using metric units (kph, not mph)‏
public void setSpeed(double newSpeed) {
  setSpeedInKPH = convert(newSpeed);
public void setSpeedInKPH(double newSpeed) {
  speedInKPH = newSpeed;
You can perform arbitrary side effects
If users of your class accessed the fields directly, then they would each be responsible for executing side effects. Too much work and runs huge risk of having display inconsistent from actual values.
public double setSpeed(double newSpeed) {
  speed = newSpeed;

Example: JavaBeans

public class Currency {
  private Locale locale;
  private double amount;
  public Currency() {
     locale = null;
     amount = 0.0;
  public void setLocale(Locale l) {
     locale = l;
  public void setAmount(double a) {
     amount = a;
  public String getFormat() {
      NumberFormat nf =
      return nf.format(amount);

Why Use JavaBeans in JSP Page?

A JSP page can create and use any type of Java programming language object within a declaration or scriptlet like following.

1. Scriptlet Example:

  ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
  // If the user has no cart, create a new one
  if (cart == null) {
      cart = new ShoppingCart();
      session.setAttribute("cart", cart);

JSP pages can use JSP elements to create and access the object that conforms to JavaBeans conventions.

2. JavaBean Example:
<jsp:useBean id="cart" class="cart.ShoppingCart" scope="session"/>

Create an instance of “ShoppingCart” if none exists, stores it as an attribute of the session scope object, and makes the bean available throughout the session by the identifier “cart”

Which one is better method?

As you can tell JavaBeans based JSP code is a lot more simpler and easy to understand and would be easier to maintain.  In other words,  for web page authors, using JavaBeans syntax is a lot easier than writing Java code.

  • No need to learn Java programming language for page designers
  • Stronger separation between content and presentation
  • Higher re usability of code
  • Simpler object sharing through built-in sharing mechanism
  • Convenient matching between request parameters and object properties

Using Beans – Basics


In the simplest case, this element builds a new bean. It is normally used as follows:
<jsp:useBean id=”beanName” />

  • <jsp:useBean id=”name” />
  • Allow instantiation of Java classes without explicit Java programming (XML-compatible syntax)‏
  • Simple interpretation:
    • <jsp:useBean id=”book1″ />
    • can be thought of as equivalent to the scriptlet
    • <% coreservlets.Book book1 = new coreservlets.Book(); %>
  • But jsp:useBean has two additional advantages:
    • It is easier to derive object values from request parameters
    • It is easier to share objects among pages or servlets


This element reads and outputs the value of a bean property. It is used as follows:
<jsp:getProperty name=”beanName“ property=”propertyName” />

  • <jsp:getProperty name=”name” property=”property” />
  • Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java programming
  • <jsp:getProperty name=”book1″ property=”title” /> is equivalent to the following JSP expression

<%= book1.getTitle() %>


This element modifies a bean property (i.e., calls a method of the form setXxx). It is normally used as follows:
<jsp:setProperty name=“beanName” property=“propertyName“ value=”propertyValue” />

  • <jsp:setProperty name=”name“ property=”property“ value=”value” />
  • Allow setting of bean properties (i.e., calls to setXxx methods) without explicit Java programming
  • <jsp:setProperty name=”book1“ property=”title“ value=”Core Servlets and JavaServer Pages” /> is equivalent to the following scriptlet <% book1.setTitle(“Core Servlets and JavaServer Pages”); %>


  • Beans installed in normal Java directory …/WEB-INF/classes/directoryMatchingPackageName
  • Beans (and utility classes) must always be in packages!

Example Bean

Example JSP page

<jsp:useBean id="stringBean“ />
  <LI>Initial value (from jsp:getProperty):
  <jsp:getProperty name="stringBean“ property="message" />
  <LI>Initial value (from JSP expression):
  <I><%= stringBean.getMessage() %></I>
  <jsp:setProperty name="stringBean“  property="message"
  value="Best string bean: Fortex" />
  Value after setting property with jsp:setProperty:
  <jsp:getProperty name="stringBean“ property="message" />
  <% stringBean.setMessage
  ("My favorite: Kentucky Wonder"); %>
  Value after setting property with scriptlet:
  <I><%= stringBean.getMessage() %></I>


Setting JavaBeans Properties

jsp:setProperty syntax depends on the source of the property

  1. <jsp:setProperty name=”beanName” property=”propName” value=”string constant”/>
  2. <jsp:setProperty name=”beanName” property=”propName” param=”paramName”/>
  3. <jsp:setProperty name=”beanName” property=”propName”/>
  4. <jsp:setProperty name=”beanName” property=”*”/>
  5. <jsp:setProperty name=”beanName” property=”propName” value=”<%= expression %>”/>

Getting JavaBeans Properties & and Convert into String and insert into out

There are several ways to retrieve JavaBeans component properties. Two of the methods (the jsp:getProperty element and an expression) convert the value of the property into a String and insert the value into the current implicit out object:

  • <jsp:getProperty name=”beanName” property=”propName”/>
  • <%= beanName.getPropName() %>

For both methods, beanName must be the same as that specified for the id attribute in a useBean element, and there must be a getPropName method in the JavaBeans component.

Getting JavaBeans Properties without Converting it to String

If you need to retrieve the value of a property without converting it and inserting it into the out object, you must use a scriptlet:

  • <% Object o = beanName.getPropName(); %>

Note the differences between the expression and the scriptlet; the expression has an = after the opening % and does not terminate with a semicolon, as does the scriptlet.

Sharing Beans

You can use the scope attribute to specify additional places where bean is stored. Still also bound to local variable in _jspService

  • <jsp:useBean id=” test”  class=”abc” scope=”scope” />

Lets multiple servlets or JSP pages share data. Also permits conditional bean creation. Creates new object only if it can’t find existing one

Scope Attribute

  • ©page (<jsp:useBean … scope=”page”/> or <jsp:useBean…>)‏
    • Default value. Bean object should be placed in the PageContext object for the duration of the current request. Lets methods in same servlet access bean
  • ©Application (<jsp:useBean … scope=”application”/>)‏
    • Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()).
    • ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined).
  • ©session (<jsp:useBean … scope=”session”/>)‏
    • Bean will be stored in the HttpSession object associated with the current request, where it can be accessed from regular servlet code with getAttribute and setAttribute, as with normal session objects.
  • ©request (<jsp:useBean … scope=”request”/>)‏
    • Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute

Conditional Bean Operations

  • ©Bean conditionally created
    • jsp:useBean results in new bean being instantiated only if no bean with same id and scope can be found.
    • If a bean with same id and scope is found, the preexisting bean is simply bound to variable referenced by id.
  • ©Bean properties conditionally set
    • <jsp:useBean … />  replaced by
    • <jsp:useBean …>statements</jsp:useBean>
    • The statements (jsp:setProperty elements) are executed only if a new bean is created, not if an existing bean is found.


<jsp:useBean id="counter"
  <jsp:setProperty name="counter“ property="firstPage"
  value="SharedCounts1.jsp" />
Of SharedCounts1.jsp (this page),
<A HREF="SharedCounts2.jsp">SharedCounts2.jsp</A>, and
<A HREF="SharedCounts3.jsp">SharedCounts3.jsp</A>,
<jsp:getProperty name="counter" property="firstPage" />
  was the first page accessed.
  Collectively, the three pages have been accessed
<jsp:getProperty name="counter" property="accessCount" />
<jsp:setProperty name="counter“ property="accessCountIncrement“ value="1" />
Tagged with: JAVA

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.