The <jsp:useBean>
tag in JavaServer Pages (JSP) is used to instantiate a JavaBean, which is a reusable component that follows the JavaBeans convention (i.e., it has a no-argument constructor, and getter and setter methods for properties). The <jsp:useBean>
tag allows you to create or access a JavaBean in your JSP page, and optionally set its properties.
Here’s a breakdown of the syntax for the <jsp:useBean>
tag:
id
: The name by which the bean is referenced in the page.class
: The fully qualified class name of the JavaBean (e.g.,com.example.MyBean
).scope
: The scope of the bean (optional). This can be one of the following:page
(default) – The bean is created for the current page request.request
– The bean is created for the current request.session
– The bean is created for the current session.application
– The bean is created for the entire web application (ServletContext).
Example 1: Basic Usage of <jsp:useBean>
In this example, we will create a simple JavaBean called Person
, instantiate it using <jsp:useBean>
, and display its properties.
JavaBean (Person.java)
JSP Page (index.jsp)
Explanation:
- The
<jsp:useBean>
tag is used to create or find thePerson
bean. - The
id="person"
attribute defines the name by which the bean can be accessed in the JSP page. - The
<jsp:setProperty>
tag is used to set thename
andage
properties of thePerson
bean. - The
<jsp:getProperty>
tag is used to retrieve and display the properties of thePerson
bean.
When the index.jsp
page is accessed, it will display:
Example 2: Using <jsp:useBean>
with Request Scope
In this example, we will store the Person
object in the request
scope, which means the bean will be available throughout the duration of the current request.
JSP Page (requestExample.jsp)
Displaying the Bean's Properties (displayPerson.jsp)
Explanation:
- In the
requestExample.jsp
page, thePerson
bean is created in therequest
scope using<jsp:useBean>
. - We then set the properties
name
andage
using<jsp:setProperty>
. - The request is forwarded to
displayPerson.jsp
, where the properties of thePerson
bean are displayed using<jsp:getProperty>
.
Example 3: Using <jsp:useBean>
with Session Scope
If you want to store the JavaBean in the session scope (so it persists across multiple requests), you can set the scope
to session
.
In this case, the person
object will be available in the session and can be accessed across multiple requests within the same session.
Summary
<jsp:useBean>
is used to instantiate and manage JavaBeans in JSP pages.- It can create a new bean or access an existing one in various scopes (page, request, session, application).
- The bean's properties can be set using
<jsp:setProperty>
and retrieved using<jsp:getProperty>
.
Comments
Post a Comment