This Java tip illustrates a method of 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:
<jsp:useBean
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:
<jsp:useBean
<%-- this body is executed only if the bean is created --%>
<%-- intialize bean properties --%>
<jsp:setProperty
</jsp:useBean>
The value of a bean property can be included in the generated output using the
jsp:getProperty action:
<jsp:getProperty
<jsp:getProperty
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:
<%
if (myBean.getProp1() % 2 == 0) {
out.println("<font color=\"red\">"+myBean.getProp1()+"</font>");
} else {
out.println("<font color=\"green\">"+myBean.getProp1()+"</font>");
}
%>
Here is the bean used in the example:
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;
}
}
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.