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
1class
Designates the full package name of the bean.
2type
Specifies the type of the variable that will refer to the object.
3beanName
Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.

Example

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

/* File: TestBean.java */
package action;

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

   public String getMessage() {
      return(message);
   }
   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 −

<html>
   <head>
      <title>Using JavaBeans in JSP</title>
   </head>
   <body>
      <center>
         <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" />
      </center>
   </body>
</html>

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

Using JavaBeans in JSP

Got message....
Hello JSP...

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements