How to use action in JSP?


The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows −

<jsp:useBean id = "myName" ... />
...
<jsp:getProperty name = "myName" property = "someProperty" .../>

Following table lists out the required attributes associated with the getProperty action −

Sr.No.Attribute & Description
1name
The name of the Bean that has a property to be retrieved. The Bean must have been previously defined.
2property
The property attribute is the name of the Bean property to be retrieved.

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

674 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements