jsp: useBean Tag

The jsp: useBean tag is used to declare and initialize the bean object. The java bean object should be declared first so that the user can interact with the javaBean components by using the action tags in the JSP page. Bean is considered as the object of javaBean component.

The following is the syntax of jsp: useBean tag:

SYNTAX:

< jsp: useBean id = “name of bean” class = “name of class” scope = “page | request | session | application” >

In the above syntax the attribute id is used to define the name of the bean. It should be noted here that bean is an object of the javaBean component. The scope attribute is used to specify that where the bean is going to be stored. The class attribute is used to specify the name of the class.

Consider the following line of code in which there is useBean declaration:

CODE:

< jsp: useBean id = ” FirstBean” class = “EmployeeBean” scope = “request” / >

This line of code can be written in java code as follows:

CODE:

EmployeeBean FirstBean = (EmployeeBean) request. getAttribute (“FirstBean”);

if(FirstBean == null)

{

   FirstBean = new EmployeeBean ();

   request. setAttribute(“FirstBean”, FirstBean);

}

It should be noted here that we have the setter and getter methods in the java code. In the above code if the bean is created and we have used the useBean tag with a body then the content in the body will be executed but if the bean already exists in the named scope then the body will be skipped.

 

Example:

Consider the following example in which we have used the useBean tag to declare and to initialize the bean object, the following code has an EmployeeBean class and is considered as the JavaBean Component:

EmployeeBean. java:

import java.io.Serializable;

public class EmployeeBean implements Serializable

{

 private String n;

  public EmployeeBean()

   {

    this. n = “”;

   }

   public void settingName (String n)

   {

    this. n = n;

   }

   public String gettingName ()

   {

    return n;

   }

}

asd.jsp:

< html >

< head >

< title >JSP Page < /title >

</ head >

<jsp: useBean id = “employee” class = “EmployeeBean” scope = “request” / >

< body >

Beans

</ body >

</ html >

In the above example the jsp: useBean tag is used to declare a bean named as “employee” in the JSP page.