How to use action in JSP?

The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.

The simplest way to load a bean is as follows −

<jsp:useBean id = "name" class = "package.class" />

Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve the bean properties.

Following table lists out the attributes associated with the useBean action −

Sr.No.Attribute & Description
Designates the full package name of the bean.
Specifies the type of the variable that will refer to the object.
Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.


Let us define a test bean that will further be used in our example −

/* File: */
package action;

public class TestBean {
   private String message = "No message specified";

   public String getMessage() {
   public void setMessage(String message) {
      this.message = message;

Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and the CLASSPATH variable should also be set to this folder −

Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter −

      <title>Using JavaBeans in JSP</title>
         <h2>Using JavaBeans in JSP</h2>
         <jsp:useBean id = "test" class = "action.TestBean" />
         <jsp:setProperty name = "test" property = "message" value = "Hello JSP..." />
         <p>Got message....</p>
         <jsp:getProperty name = "test" property = "message" />

Let us now try to access main.jsp, it would display the following result −

Using JavaBeans in JSP

Got message....
Hello JSP...