What is < jsp:usebean >tag why it is used?

Ans: This was very popular JSP interview question during early 2000, it has lost some of its shine but still asked now and then on interviews.


JSP Syntax
<jsp:useBean
id="beanInstName"
scope="page  |  request  |  session  |  application"
class="package.class"  type="package.class"
</jsp:useBean>

This tag is used to create an instance of java bean, first of all, it tries to find out the bean if bean instance already exists assign stores a reference to it in the variable. If we specified the type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is a simple way to create a java bean.


Example:
<jsp:useBean id="stock" scope="request" class="market.Stock" />

<jsp:setProperty name="bid" property="price" value="0.0" />

a <jsp:useBean> element contains a <jsp:setProperty> 
element that sets property values in the Bean, we hava <jsp:getProperty>
element also get the value from the bean.

Explanation of Attribute:

id = "beanInstanceName"
A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another < jsp:useBean > element, the value of id must match the value of id used in the original < jsp:useBean > element.

scope="page | request | session | application"

The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:

• page – we can use the Bean within the JSP page with the < jsp:useBean > element
• request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.
• session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean exists across the entire session, and any page that participates in the session can use it.
• application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.

class="package.class"
Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor.

type="package.class"

If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext