logo

JSP: UseBean


Show

Jsp: useBean Action Tag

The jsp:useBean action tag is used to discover or instantiate a bean class. If a bean object of the Bean class is already created, it does not create the bean relying on the scope. But if an item of bean isn't always created, it instantiates the bean.

Syntax of jsp:useBean Action Tag

<jsp:useBean id= "instanceName" scope= "page ' request ' session ' application"   
class= "packageName.className" type= "packageName.className"  
beanName="packageName.className ' <%= expression >" >  
</jsp:useBean> 

Attributes and Usage of Jsp:useBean Action Tag

  1. Id: is used to become aware of the bean withinside the designated scope.
  2. scope: represents the scope of the bean. It can be a page, request, consultation, or application. The default scope is page.
  • page: specifies that you may use this bean withinside the JSP page. The default scope is page.
  • request: specifies that you may use this bean from any JSP page that strategies the identical request. It has a wider scope than the page.
  • session: specifies that you could use this bean from any JSP page withinside the identical consultation whether procedures the identical request or now no longer. It has a broader field than requested.
  • application: specifies that you may use this bean from any JSP page withinside the equal application. It has a broader field than session.
  1. class: instantiates the specified bean class (i.e. creates an item of the bean class) however it needs to have no-arg or no constructor and need to now no longer be abstract.
  2. type: gives the bean information kind if the bean already exists withinside the scope. It is specifically used with the class or beanName attribute. If you operate it without class or beanName, no bean is instantiated.
  3. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

Easy Example of Jsp:useBean Action Tag

We are simply supplicating the method of the bean class in the below given example:

Note: For instance of setProperty, getProperty, and use bean tags visit the next page.

Calculator.java (an easy bean class)

package com.javatpoint;  
public class Calculator{  

public int cube(int n){return n*n*n;}   

}

Index.jsp file

<jsp:useBean id="obj" class="com.intellinuts.Calculator"/>  

<%  
int m=obj.cube(5);  
out.print("cube of 5 is "+m);  
%> 

download this example