Transcript Chapter 6
Chapter 6
Using JavaBeans Components
in JSP Pages
What Is a Bean?
package com.ora.jsp.beans.motd;
import java.util.*;
public class CartoonBean implements java.io.Serializable {
private static int index = -1;
private List fileNames;
public CartoonBean( ) {
initFileList( );
}
public String getFileName( ) {
index++;
if (index > fileNames.size( ) - 1) {
index = 0;
}
return (String) fileNames.get(index);
}
private void initFileList( ) {
fileNames = new ArrayList( );
fileNames.add("dilbert2001113293109.gif");
...
}
}
Implement a Java Bean
use a package name
A bean class must have a no-argument
constructor
The bean properties are accessed through
getter and setter methods
the bean class should implement the
java.io.Serializable or the
java.io.Externalizable interface
The property name is case-sensitive and
always starts with a lowercase letter
Declaring a Bean in a JSP Page
<html>
<head>
<title>A dose of Dilbert</title>
</head>
<body bgcolor="white">
<h1>A dose of Dilbert</h1>
<jsp:useBean id="cartoon"
class="com.ora.jsp.beans.motd.CartoonBean" />
<img src="images/<jsp:getProperty name="cartoon"
property="fileName" />">
</body>
</html>
Reading Bean Properties
Using the <jsp:getProperty> Action
Using the JSP Expression Language
<jsp:getProperty name="cartoon" property="fileName" />
<img src="images/${cartoon.fileName}">
If you need to generate an image
dynamically, you should use a servlet
<img src="imageGenServlet?width=100&height=100">
Setting Bean Properties
Using the <jsp:setProperty> Action
<jsp:setProperty name="msg"
property="category" value="thoughts" />
Using the JSTL <c:set> Action
<c:set target="${msg}" property="category"
value="thoughts" />
To set a JSP action attribute to the value
produced by another action
<jsp:setProperty name="msg" property="category">
<jsp:attribute name="value" trim="true">
<jsp:getProperty name="myBean" property="myProperty" />
</jsp:attribute>
</jsp:setProperty>
Automatic Type Conversions
When you use the <jsp:setProperty> or the JSTL
<c:set> action, the container takes care
automatically of the conversion from text values to
the Java types
Conversion of text value to
property type
Property type
Conversion method
boolean or Boolean
Boolean.valueOf(String)
byte or Byte
Byte.valueOf(String)
char or Character
String.charAt(0)
double or Double
Double.valueOf(String)
int or Integer
Integer.valueOf(String)
float or Float
Float.valueOf(String)
long or Long
Long.valueOf(String)
short or Short
Short.valueOf(String)
Object
new String(String)
Setup JavaBean
Setup Environment Variables
Compile JavaBean
Javac CartoonBean.java
Javac –classpath servlet-api.jar MyServlet.java
Create directories in classes
path %java_home%\bin;%path%
set ClassPath %java_home%\lib
com\ora\jsp\beans\motd
Copy MyBean.class to com\ora\jsp\beans\motd
Reload Web Application