Using JavaBeans with JSP. Small Introduction!

September 20, 2007

What should we know when using Java Bean? Here are the most important observations:

  • A bean class must have a constructor with no arguments. We know that an empty constructor is automatically created.
  • A bean class shouldn’t have public instance variables.
  • Persistent values should be accessed through methods called get and set. For example name=bean.getName();getName() has no arguments and return in a variable the name. Although we can use JSP scriptlets or expressions to access arbitrary methods of a class, the standard JSP methods are: the getXxx/setXxx or isXxx/setXxx.

The jsp:useBean action lets you load a bean to be used in the JSP page. Here is the syntax for specifying the using of a bean: <jsp:useBean id="name" class="MyClass" /> Here we initiate an object of the package class and bind it to the name variable. We also can attach a scope attribute that makes the bean associated with more than just the current page.

The local variable has the same type as the object created, but if we want that the variable has the type of a superclass or interface we can use the type attribute like here: <jsp:useBean id="name" class="MyClass" type="Runnable" />;

If we have created a bean we can access its properties with jsp:getProperty. For example the course class has a property called name and we have an instance called java - we can have the value of the period property like this:

<jsp:getProperty name="java" property="period" />
<%= java.getPeriod() %>

If we are not familiar with something like this we can use methods called getFoo and setFoo - this means the bean has a property of type T called foo.

Bellow is an example of a simple bean.

public class firstBean {

private String name= "";

public String getName() {

return(name);

}

public void setName(String name) {

this.name= name;

}

}

Next is an example of using JavaBeans with JSP.

<jsp:useBean id="user" class="UserData" scope="session"/>
<HTML>
<BODY>
<blx:getProperty name="user" property="*">
<FORM METHOD=POST ACTION="SaveName.jsp">
   What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
   What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
   What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</blx:getProperty>
</BODY>
</HTML>
<HTML>
<BODY>
<jsp:useBean id="user" class="UserData" scope="session"/>
<blx:setProperty name="user" property="*" onError="errorHandler"/>
<%
  pageContext.include( "GetName.jsp" );
%>
</BODY>
</HTML>

 

Post a comment

Name (required)

Mail (will not be published) (required)

Website

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word