A Java Bean is a class that meets the following requirements:
All standard Java classes can be used as beans.
<jsp:useBean id="name" class="package.class" />
Example
<%@ page language="java" contentType="text/html" %> <HTML> <HEAD> <TITLE>JSP: Beans Example 1</TITLE> </HEAD> <BODY BGCOLOR="WHITE"> <H1>JSP: Example of using a Bean</H1> <jsp:useBean id="today" class="java.util.Date" /> The current date and time is: <UL> <LI> Date: <jsp:getProperty name="today" property="date" /> <LI> Month: <jsp:getProperty name="today" property="month" /> <LI> Year: <jsp:getProperty name="today" property="year" /> <LI> Hours: <jsp:getProperty name="today" property="hours" /> <LI> Minutes: <jsp:getProperty name="today" property="minutes" /> </UL> </BODY> </HTML>
<jsp:getProperty name="objectName" property="propertyName" %>
<jsp:setProperty name="objectName" property="propertyName" value="value" />
Example Bean
package ecom; public class SecretMessage { private String message = "No message."; public String getMessage() { return message; } public void setMessage(String s) { message = s; } }
<HTML> <HEAD> <TITLE>Using the SecretMessage Bean</TITLE> </HEAD> <BODY BGCOLOR="WHITE"> <H1>Using the Secret Message Bean</H1> <jsp:useBean id="MyMessage" class="ecom.SecretMessage" /> <OL> <LI> Initial Message (using getProperty): <I> <jsp:getProperty name="MyMessage" property="message" /> </I> <LI> <jsp:setProperty name="MyMessage" property="message" value="Meet me at the Foggy Bottom Metro" /> Secret message (after setting): <I> <jsp:getProperty name="MyMessage" property="message" /> </I> </OL> </BODY> </HTML>
EXERCISE
Enter the code above and try it. You will need to compile the bean class and place it in the appropriate place for you server. For example, Apache Tomcat requires it to be in the directory
install_dir/webpages/WEB-INF/classes/ecom/SecretMessage.class
Another example of using the SecretMessage bean.
<HTML> <HEAD> <TITLE>Using the SecretMessage Bean version 2</TITLE> </HEAD> <BODY BGCOLOR="WHITE"> <H1>Using the Secret Message Bean (Version 2)</H1> <jsp:useBean id="MyMessage" class="ecom.SecretMessage" /> <OL> <LI> Initial Message: <I> <jsp:getProperty name="MyMessage" property="message" /> </I> <LI> <jsp:setProperty name="MyMessage" property="message" value='<%= request.getParameter("Message") />' /> Secret message: <I> <jsp:getProperty name="MyMessage" property="message" /> </I> </OL> </BODY> </HTML>
EXERCISE
Enter the code above in a file called Bean2.jsp and try it using the following URL:
Parameter values (as in form input) can also use the syntax:
<jsp:setPropoerty name="MyMessage" property="message" param="Message" />
EXERCISE
Replace the line in Bean2.jsp to use the above.
For multiple parameters that are matched one-to-one with bean properties, you can also use the syntax:
<jsp:setPropoerty name="MyMessage" property="*" />