Using a Bean in a JSP Page
To use a bean in a JSP page, three attributes must be supplied an
id, which provides a local name for the bean, the bean's class name,
which is used to instantiate the bean if it does not exit, and a
scope, which specifies the lifetime of the bean.
There are four scopes available page, request, session, and
application. A page-scoped bean is available only within the JSP page
and is destroyed when the page has finished generating its output for
the request. A request-scoped bean is destroyed when the response is
sent. A session-scoped bean is destroyed when the session is
destroyed. An application-scoped bean is destroyed when the web
application is destroyed.
This example retrieves a session-scoped bean and makes it available
using the id myBean. The bean is automatically
created if it does not exist:
If it is necessary to initialize the bean after it is created, the
initialization code can be placed in the body of the jsp:useBean action.
The body will not be executed if the bean already exists.
Here is an example:
The value of a bean property can be included in the generated output
using the jsp:getProperty action:
The jsp:useBean action also declares a local Java variable to hold
the bean object. The name of the local variable is exactly the value
of the id attribute. Here is an example that accesses the bean
within a scriptlet:
Here is the bean used in the example:
<jsp:useBean id="myBean" class="com.mycompany.MyBean" scope="session" />
<jsp:useBean id="myBean2" class="com.mycompany.MyBean" scope="session">
<%-- this body is executed only if the bean is created --%>
<%-- intialize bean properties --%>
<jsp:setProperty name="myBean2" property="prop1" value="123" />
</jsp:useBean>
<jsp:getProperty name="myBean" property="prop1" />
<jsp:getProperty name="myBean" property="prop2" />
<%
if (myBean.getProp1() % 2 == 0) {
out.println("<font color=\"red\">"+myBean.getProp1()+"</font>");
} else {
out.println("<font color=\"green\">"+myBean.getProp1()+"</font>");
}
%>
package com.mycompany;
public class MyBean {
// Initialize with random values
int prop1 = (int)(Integer.MAX_VALUE*Math.random());
String prop2 = ""+Math.random();
public int getProp1() {
return prop1;
}
public void setProp1(int prop1) {
this.prop1 = prop1;
}
public String getProp2() {
return prop2;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
}
Post a comment