How to use action in JSP?

The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action −

You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below −

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

In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as given below −

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

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

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

Sr.No.Attribute & Description
Designates the bean the property of which will be set. The Bean must have been previously defined.
Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored.
The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither.


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...

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started