JavaBeans and
JSPs
Peter Komisar v. 3.2
© Conestoga College
reference: JavaServer
PagesTM Fundamentals Short Course,Govind Seshadri
http://developer.java.sun.com/servlet/PrintPageServlet,
The J2EE Tutorial,
Java Server Pages, Stephanie
Brodoff, Java ServerPages 1.2 Syntax Card,
http://java.sun.com/products/jsp/pdf/card12.pdf,
'Web
Development with
Java Server Pages' D.Fields, M.Kolb& S.Bayern
Java Beans Overview
Java Bean Benefits
JavaBeans bring the benefits of
modularization and separation
of presentation from implementation. While scriptlets are fine,
and one can even enjoy their directness, a popular goal of
modern developers is to separate the presentation code from
code that supplies
processing. This allows each to easily be
modified independently. This facilitates division of labor.
The JSP component model is based on the
JavaBean.
Components attempt to 'black box' functionality where it's
inputs and outputs are all a user has to know to use the
component.
JavaBean
Background
The JavaBean API provides a strict specification that a Java
class has to adhere to in order for it to be called a bean. This
specification
dictates how properties, behaviour and events
need to be configured. The predictability of the patterns used
allows bean containers to access,
query and modify the state
of a bean.
The API uses a process called
'reflection' to determine what
a beans properties are. The API also uses the process of
serialization to store a bean in a stateful condition.
//
Introspection is a specialized use of the reflection
process and describes
// the process of finding
what properties, methods and
events a Bean support
Builder tools, more recently called containers are able to load,
configure and query a bean based on the expected syntax
dictated by the JavaBean API.
These tools usually supply visual
GUIs that allow beans to be dragged
and dropped onto a screen
where they can be composed into whole applications without the
need to code Java.
Difference
Kinds of JavaBeans
Generally speaking there is a difference
between the type
of JavaBeans that is used with JSPs and with GUIs. Beans
may be described as having evolved in three or four
categories.
Visual Component
JavaBeans
All AWT and Swing visual components are
JavaBeans and take
advantage of the full specification. Tools like the bean box expect
these
components to be fully compliant with the API with respect
to their properties,
method patterns and event coding. Java's
JFrame is an example of
this variety of JavaBean.
Data & Service
Beans
These sorts of bean, are used to carry data or
to provide some
function, are the sort of bean that are described as auxillary
components to be used
in the J2EE specification. They can be
used in conjunction with JSPs, servlets
or Enterprise JavaBeans.
While nothing stops them technically from using
the different
aspects of the JavaBean specification, in practice they make
simple use of the JavaBean patterns.
.
Data beans will typically be comprised of read-only properties
or a mix
of read-only and read-write properties that are accessible
through public
methods.Service beans are behavioural in nature,
having evolved to supply a
service such a database access or a
financial calculation.
Enterprise JavaBeans
Although they are described as JavaBeans
because they do
use similar get set naming patterns they are really quite unique.
They run in the
context supplied by a container, have life cycle
methods and are built largely
on RMI or The Java Remote
Method API. They have little obvious similarity to the JavaBeans
we popularly think of when thinking of Java Server
Pages or
visual components for that matter.
JSPs Use Data or
Service Beans
Bean Properties
In order for a tool to learn about a Bean's member parts, say
to fill a property sheet for presentation to an application user,
the bean has been composed in a way that enables an
introspective tool to retrieve the bean's internal information.
The following patterns for four categories of properties
accomplishes this.
Simple Properties //
getter/setters aka acessor/mutator
Simple properties are those that can be
described
by a
get/set method pair as
shown in the following forms. The
first shows
the patterns used for read-write properties.
Notice how the actual property name is inserted after
the
set or get prefix. Java naming conventions apply where the
name of the method starts lowercase and subsequent full
words are started in caps. Set methods take the property
as an argument and return void while get methods take no
arguments and return the property type. Note, a read-write
property is created by supplying both get and set methods.
Read-only properties are created by simply providing the
getter method for the
property.
Method Form Used for Simple Properties
public void setPropertyName
(
Property_type,
property_value )
Property_type getPropertyName(
)
Accessor
Mutators Examples For a String property Called 'description'
public void setDescription(String
description ){
this.description=description;
}
public String getDescription( ){
return this.description;
}
For boolean properties a variation is allowed
using
the prefix 'is' in the getter form of a method that returns
boolean. This allows the reading 'isSomething true'.
The following form shows this.
Method Form Used for Simple Properties Returning 'boolean'
public void setPropertyName
( boolean property_value )
boolean isPropertyName(
){
/*body*/ }
Accessor
Mutators Examples For a boolean property Called 'confirmed'
public void setConfirmed(boolean
confirmed ){
this.confirmed=confirmed;
}
public boolean isConfirmed( ){
return this.confirmed;
}
Indexed Properties
Indexed properties are plural versions of the
simple form
methods where instead
of a simple value an array is taken
or returned.
The JavaBean specification allows creating
indexed property methods that set and return whole arrays
r set and return single values of the array using an index.
The index is specified as a second parameter
to the set
method and as the single parameter to the get method.
Following are the forms of the indexed methods.
Method Form of an Indexed
Property
public void setPropertyName
(<PropertyType>[ ]
value)
public
PropertyType[] getPropertyName( )
//
Methods to access individual values
public void setPropertyName
(int
index, PropertyType_value)
public <PropertyType>
getPropertyName(int
index)
Accessor
Mutators Example For a An Indexed Property Called 'memos'
public void setMemos(int index,int value ){
this.memos[index]=value;
}
public int getMemos(int index ){
return this.memos[index];
}
// shows the
form that uses an index to get and set a single value of the array
JSPs Do Not Expose Compound Properties
JSPs do not supply a
mechanism to expose compound
properties. Code via a scriptlet needs to be provided that
loops through the values of the
indexed property or a
custom tag designed to do that.
Example
<% for( int i=0; i< memos.length; i++){
%>
<%= conference.getMemos(i) %>
<% } %>
Bound and Constrained Property Types //
just for reference
There are two other property
types described in the JavaBean
specification. Bound
properties register listeners
that can be
notified of a property change to itself. The listener
components
can react in some appropriate
manner. Constrained properties
are like bound properties however
they allow a listener to 'veto'
a change by throwing a 'PropertyVetoException'.
These properties
are used primarily with the visual variety of JavaBeans. It
is not
common to see theses property types used with beans in
conjunction with JSPs.
Creating a Complete JSP JavaBean
Other Characteristics of a Java
Bean
Practically speaking, once the private properties and the
public get / set
methods have been created, a JavaBean
of the data variety is nearly finished.
The JavaBean is
required to include a no-args constructor and be packaged
like any other regular Java class. No special extensions or
interface implementations are required.
One other convention, the JavaBean typically has it's
name
adjoined by the 'Bean' suffix. For example, if a class called
'Translator' was also designed to act as a JavaBean, it
would be called
'TranslatorBean'.
//
no-arg constructor, naming convention & no special extensions
The following example is a JavaBean. Notice the presence
of a main
method is permissible in beans even if not
recommended. This is allowed as non-bean methods are
free to be included in bean. They just will not participate
in
the bean pattern. The main( ) method is included here to
test the
methods before they are deployed into the bean
environment. The main method would be removed in a
standard data bean.
//
testing methods in a standalone application may simplify JSP Bean
// development as the error trails of
the two code bases are not mixing.
Standalone Java Code to Test Beans Methods
public class ConferenceBean{
private String description;
private boolean confirmed;
private int[] memos;
/* Bean
no-args constructor */
public ConferenceBean( ){
description="available";
memos=new int[]{10034,10065,10077};
// boolean is set to false by
default
}
// public
accessor mutator methods
public void setDescription(String description ){ //description
this.description=description;
}
public String getDescription( ){
return this.description;
}
public void setConfirmed(boolean confirmed ){ // confirmed
this.confirmed=confirmed;
}
public boolean isConfirmed( ){
return this.confirmed;
}
public void setMemos(int index,int value ){ // memos[]
this.memos[index]=value;
}
public int getMemos(int index ){
return this.memos[index];
}
public static void main(String[]args){
ConferenceBean cf = new ConferenceBean();
System.out.println( "Testing Bean Methods");
System.out.println( "********************");
System.out.println("Description Before setXXX(); " +
cf.getDescription());
System.out.println("Confirmed Before setXXX(): " +
cf.isConfirmed());
System.out.println("Memos 3rd Element Before setXXX(): " +
cf.getMemos(2));
// Reset
cf.setDescription("Toronto Convention Center");
cf.setConfirmed(true);
cf.setMemos(2,11115);
System.out.println( "********************");
System.out.println("Description After SetXXX(); " +
cf.getDescription());
System.out.println("Confirmed After SetXXX(): " +
cf.isConfirmed());
System.out.println("Memos 3rd Element After SetXXX(): " +
cf.getMemos(2));
}
}
}
Output
C:\JSP\Java>java
ConferenceBean
Testing
Bean Methods
********************
Description
Before setXXX(); available
Confirmed
Before setXXX(): false
Memos 3rd
Element Before setXXX(): 10077
********************
Description
After SetXXX(); Toronto Convention Center
Confirmed
After SetXXX(): true
Memos 3rd
Element After SetXXX(): 11115
|
Referencing
JavaBeans From JSP
Pages
Using JavaBean Components
Now that we have a JavaBean we need to consider how to
reference it from inside a JSP page. If you had a chance
to look at the standalone code above you will have seen
that the bean needed to be created before it before it was
referenced.
When the <jsp:useBean > tag is introduced into a
JSP
page the action of instantiating the bean class is done
automatically, if
the bean has not already been instantiated.
The useBean can be used in a simple way or in a more
complex
form. The form for this action shows all the
possibilties.
Form of the jsp:useBean Tag
<jsp: useBean id=" beanInstanceName "
scope=" page | request | session | application"
{
class=" package. class " [ type=" package. class "] |
beanName="{ package. class | <%= expression %>}"
type=" package. class "| type=" package. class "
}
{/> | > other elements </
jsp: useBean> }
// Reference:
JSP tags that
use the jsp prefix are the
// same for both XML & HTML JSPs
To provide a concrete example,
ConferenceBean above,
would be referenced into a JSP page with the following
useBean tag.
// once tested the main( ) method can be
removed
Example
<jsp:useBean id="conference"
class=" ConferenceBean" />
Quick Tour of <jsp:useBean>
Attributes
The 'id'
Attribute
The 'id' attribute is assigned a name that is a unique value
inside
the JSP page. There are constraints on this identifier.
It must be unique, case-sensitive, the first letter must be a
character and subsequent letters must be letters, numbers
or underscores. // no
$ symbols as in Java
The class
Attribute
You specify the Java class name to this attribute. This
name has to be fully qualified and include it's classpath
through it's packages. By convention authors may use
their domain names as top level packaging units.
Example
<jsp:useBean id="translator" class="form.TranslatorBean" />
The type
Attribute
The type attribute allows specifying the type the class will be
instantiated to. This accomodates the Java idea that you can
instantiate a class
object to the type of a parent or interface
that the class implements. This
attribute is unlikely to be used
much in JSPs. Assume a generic Translator was parent of a
FrenchTranslator. It could be instantiated as follows.
Example
TranslatorBean translator = new FrenchTranslatorBean( );
It would then be defined in an associated JSP page as follows.
Example
<jsp:useBean id="trans" class="FrenchTransBean" type="TransBean"
/>
The beanName
Attribute
As an alternative to specifying a value to the class attribute,
the 'beanName' can be used. This is tag is not seen much.
It passes a name to the JSP engine which will in turn pass
the name to the instantiate( ) method of the java.beans.Beans
class. This
attribute can be assigned at run-time so a resource
can be specified via a request parameter.
The scope
Attribute
We saw that scopes were
associated with each of the
four implicit objects that can hold attributes. The default
scope is page
scope.
page
bean
- A page bean is instantiated anew everytime
a request is passed to the page. A page bean is transient
and will not persist between requests.
request
bean
- A request bean cannot come on a request
which only carries name value pairs. A request bean can
only be stored on the request object though the actions of
a JSP or servlet.
session
bean
- A session bean is a Java object that
provides a significant form of persistence. A session
continues to exist beyond the scope of an initial request.
Example
<jsp:useBean id="member" class="club.Member" scope="session" />
A nice feature of JSPs, just the act of declaring a bean in
'session' scope automatically stores the bean in the session
object. We don't have to do any explicit programming.
application
bean - An application bean persists for the
length of the of the web application. Application scope
would be used to persist beans that would be useful to
members of the application over the length of the
applications life span.
Using the <jsp:useBean > Tag's Body Area
The
<jsp:useBean>
tag can also optionally include a body,
such as is shown in the following Magelang Institute example.
Magelang Institute Example
<jsp:useBean id="user" class="com.jguru.Person" scope="session" >
<%
user.setDate(new Date( ).toString( ));
//etc..
%>
</jsp:useBean>
// the body in this form is
only executed when the bean is instantiated.
One Time Initialization
The
body section of the useBean is roughly analogous to the
action of the class constructor. Any scriptlet or
<jsp:setProperty>
tags present within the body of a <jsp:useBean> tag is executed
only once when
the
bean is instantiated, acting as an initializer
for bean's properties.
The
<jsp:getProperty > & <jsp:setProperty > Actions
Once you have declared a JavaBean component, you have
access to its properties to customize it. The jsp:getProperty
and jsp:setProperty tags are the tag equivalent of using the
JavaBean get and set methods.
A bean property value is accessed
using the <jsp:getProperty>
tag. With the <jsp:getProperty> tag,
you specify bean's id to
the name attribute and the
name of the property whose value
you are interested in to the property attribute. The actual value
is
then directly printed to the output. In this way the action of the
jsp:getProperty action is similar to the actions of a
expression
tag.
Example
<jsp:getProperty name="conference" property="name" />
// the value of
jsp:getProperty is written directly to output similar to how
// expression tags send results directly to output
The <jsp:setProperty > tag changes the property value of a
JavaBean component.When using this tag, the bean and the
property are
identified and the value that the property will be
changed to is assigned to the
'value' attribute.
Magelang Institute Example
<jsp:setProperty name="user" property="name" value="jGuru" />
Initializing JavaBeans With Form
Parameters
From <jsp:setProperty>
First we create a JavaBean
that will service our property
queries. Following is a JavaBean class called MemberBean.
We follow convention and name it with a Bean suffix.
Example of a MemberBean
public class MemberBean{
private String last;
private
String first;
private int num;
/* Bean
no-args constructor */
public MemberBean( ){
last="name please";
first="name or initial";
// int set to 0 by default
}
// public
accessor mutator methods
public void setLast(String last
){
//last
this.last=last;
}
public String getLast( ){
return this.last;
}
public void setFirst(String first
){ // first
this.first=first;
}
public String getFirst(){
return this.first;
}
public void setNum(int num ){ // num
this.num=num;
}
public int getNum( ){
return this.num;
}
}
Pitfalls
To Watch For!
Two significant
pitfalls were encountered in using
the JavaBean.
First, while
documentation to say so, is not common, it
appears that it is expected that JavaBeans be housed
in a declared package.
Second, with respect
to using Eclipse, the IDE expects
you to create first a new package for any classes that
will be declared as belonging to that package. You will
find the package icon, under File --> New --> Other as
you have for other components you have built.
Consider the following form
with three parameters called lastName,
firstName and number.
Member HTML Submission Class
<html>
<head>
<title>Member</title>
</head>
<body>
<H1> Member </H1><HR/>
<form action="MembersJ.jsp">
Last Name: <input type="text" name="lastName" />
First Name: <input type="text" name="firstName"/>
Number: <input type="text" name="number"/>
<input type=submit name="Submit">
</form>
</body>
</html>
The JSP engine will parse out these parameters and place
use them to initialize a JavaBean called MemberBean using
the following form of setProperty tag. Notice the param tag
effectively maps the corresponding parameter value to the
specified bean property.
//
the following JSP assumes your bean is in a beans
// package that you have previously
created and put
// your bean in.
JSP Example
<html>
<body>
<H3> Member Confirmation </H3>
<jsp:useBean id="member" class="beans.MemberBean" >
<jsp:setProperty name="member" property="last"
param="lastName" />
<jsp:setProperty name="member" property="first"
param="firstName" />
<jsp:setProperty name="member" property="num" param="number"
/>
</jsp:useBean >
Your Last name:
<jsp:getProperty name="member" property="last" />
Your First name:
<jsp:getProperty name="member" property="first" />
Your Number:
<jsp:getProperty name="member" property="num" />
</body>
</html>
Wild Carding
request Parameters to Bean Properties
If the form names match the JavaBean property names, JSP
supplies a short cut where the engine will parse all the incoming
values from
the HTML form elements that are part of the request
object and assign
them to the corresponding set of bean properties.
The following single statement achieves this.
<jsp:setProperty name="user" property="*"/>
The developer should
be careful to consider making sensitive values read-only
Magelang JSP Code
Sample
Following is the Magelang Institute form JSP example. This
page
aside from being nicely composed from a presentation
point of view, is interesting
because the same document
serves as both form submitter and result
template.
//
some modifications to paths and packages to make it easy to run
// an orphan <p> tag was removed
Form.jsp // from JGuru,
Magelang Institute
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body
bgcolor="#c8d8f8">
<form action="MageJSP.jsp" method=post>
<center>
<!-- form sends the action to this page-->
<table cellpadding=4 cellspacing=2 border=0>
<!-- form values are ordered in a table -->
<th bgcolor="#CCCCFF" colspan=2>
<font size=5>User Registration</font>
</th>
<tr>
<td valign=top>
<b>First Name</b>
<br>
<input type="text" name="firstName"
size=15></td> <!-- property 1 -->
<td valign=top>
<b>Last Name</b>
<br>
<input type="text" name="lastName" size=15></td> <!-- property 2 -->
</tr>
<tr>
<td valign=top colspan=2>
<b>E-Mail</b>
<br>
<input type="text" name="email"
size=20> <!-- property 3 -->
<br></td>
</tr>
<tr>
<td valign=top colspan=2>
<b>What languages do you program in?</b>
<br> <!-- property 4
-->
<input type="checkbox" name="languages"
value="Java">Java
<input type="checkbox" name="languages"
value="C++">C++
<input type="checkbox" name="languages" value="C">C<br>
<input type="checkbox" name="languages"
value="Perl">PERL
<input type="checkbox" name="languages" value="COBOL">COBOL
<input type="checkbox" name="languages" value="VB">VB<br>
</td>
<!-- checkbox may result in
more which will be returned as a array
and need to use a indexed get/set method in the JavaBean -->
</tr>
<tr>
<td valign=top colspan=2>
<b>How often can we notify you regarding your interests?</b>
<br> <!-- property 5 -->
<input type="radio" name="notify" value="Weekly"
checked>Weekly
<input type="radio" name="notify"
value="Monthly">Monthly
<input type="radio" name="notify" value="Quarterly">Quarterly
<br></td>
</tr>
<tr>
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset"
value="Reset">
</td>
<!-- submit and reset-->
</tr>
</table>
</center>
</form>
<%-- Create the bean only when the form is posted --%> <!-- JSP type comment
-->
<%
if (request.getMethod().equals("POST")) {
%>
<!-- creates bean object if not already alive -->
<jsp:useBean id="formHandler" class="jguru.FormBean">
<jsp:setProperty name="formHandler" property="*"/> <!-- iterates form values into
bean -->
</jsp:useBean> <!-- jsp:setProperty
is nested inside jsp:useBean tags -->
<p>
<hr>
<font
color=red> <!-- response is written to same
jsp that fielded the form -->
<b>You submitted:
First
Name:</b><br> <!-- property values are
retrieved using getProperty( ) methods -->
<jsp:getProperty name="formHandler"
property="firstName"/><br>
<b>Last Name:</b><br>
<jsp:getProperty name="formHandler"
property="lastName"/><br>
<b>Email:</b><br>
<jsp:getProperty name="formHandler" property="email"/><br>
<b>Languages:</b><br>
<%
String[] lang = formHandler.getLanguages();
if (!lang[0].equals("1")) {
out.println("<ul>");
for (int i=0; i<lang.length; i++)
out.println("<li>"+lang[i]);
out.println("</ul>");
} else out.println("Nothing was selected<br>");
%>
<b>Notification:</b><br>
<jsp:getProperty name="formHandler"
property="notify"/><br> <!-- final property -->
<%
}
%>
</font>
</body>
</html>
FormBean
Sample
from JGuru,
Magelang Institute
package com.jguru;
public class FormBean {
private String firstName;
private String lastName;
private String email;
private String languages[];
private String notify;
public FormBean()
{
// initializes
in the no-arg constructor
firstName="";
lastName="";
email="";
languages = new String[] { "1" };
notify="";
}
// does all
his getXXX( )
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String[] getLanguages() {
return languages;
}
public String getLanguages(int index) { // indexed form
return languages[index];
}
public String getNotify() {
return notify;
}
public void setFirstName(String x) {
firstName = x;
}
public void setLastName(String x) {
lastName = x;
}
public void setEmail(String x) {
email = x;
}
public void setLanguages(String[] x) {
languages = x;
}
public void setLanguages(String x, int index) {
languages[index] = x;
}
public void setNotify(String x) {
notify = x;
}
}
JSPs and Database Connections
Recall we looked briefly at the basic
components of a JDBC program.
The following source code, extracted from Peter Van der Linden book
'Just Java' provides a good example of code based on using a
DriverManager.
Classic
JDBC Example // from ' Just Java '
by
Peter Van der Linden
import java.sql.*;
class simple{
public static void main(String[]args){
String url = "jdbc:odbc:myDSN" ;
String query = "SELECT * FROM Customers"
+ " WHERE CustomerID = 'QUICK' ";
try{
//
Load the jdbc-odbc bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//
Attempt to connect to a driver
Connection con =
DriverManager.getConnection(
url," "," " );
//
Create a Statement object so we can submit SQL statements to the driver
Statement stmt = con.createStatement( );
//
Submit a query, creating a ResultSet object
ResultSet rs = stmt.executeQuery(query);
//
Display all columns and rows from the result set
printResultSet(rs);
rs.close( );
stmt.close( );
con.close( );
}
catch(SQLException ex){
while (ex != null){
System.out.println("SQL Exception: " + ex.getMessage( ));
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex){
ex.printStackTrace( );
}
}
private static void printResultSet(ResultSet rs) throws
SQLException{
int numCols =
rs.getMetaData(
).getColumnCount( );
while( rs.next( ) ){
for ( int i = 1; i < numCols; i ++ ){
System.out.print(rs.getString(i) + " | " );
}
System.out.println( );
}
}
}
Setting Up an MS
Data Source Name // just for reference
To run the code above
using the JDBC:ODBC bridge to connect to Microsoft's
Access database, you need to
create a DSN or Data Source Name for a file that
will be the store for an Access
Database
session.
The bulk of what needs to be
done is executed by an odbc
administration program called odbcad32.exe
found
in Windows/System (or represented
by an icon in the Control
Panel
).
Some of the key steps, 1) Use name myDSN, description anything.
For 'Add Data
Source', select 'Microsoft Access Driver ( *.mdb) Press
database 'Select' to bring
up a file chooser. Choose c:\Access\Samples\Northwind.mdb
Press OK.
.
|
Note
on how ResultSet query can be used to Load JavaBean
One of the commonest
actions when using JavaBeans with
databases is the loading of JavaBeans with row data that is
subsequently displayed or utilized inside a JSP page. With
JSP pages, as a
result set is iterated, instead of sending
code to
console as occurs in the above standalone program,
a
Javabean's setMethods( ) can be called to load row data
directly
into the JavaBean.
Example
<% page import
="java.sql.*" %>
<jsp:useBean id=member class MemberBean >
<%
//
more JDBC code
if (result.next( ) ){
member.setLastName(results.getString("LastName"));
member.setFirstName(results.getString("FirstName"));
member.setNumber(results.getInt("No");
}
// closing JDBC
code
%>
/jsp:useBean>
The DataSourceInterface // just for reference
The DataSource interface which was introduced
with JDBC 2.0
and is the
suggested replacement for the DriverManager class
shown in the above example. While it provides many advantages
when used in the Enterprise Java context such as compliance with
JNDI and support for connection
pooling and distributed transactions.
Within the context of JSPs, which model is used in our example is
not important as the access mechanics are hidden away in the bean.
Accordingly we will just use classic JDBC in the JSP examples
below.
Maintaining
Persistent Connections in a JSP Environment
Establishing a database connection is one of the slowest
parts of a web application. This leads one to want to persist
a connection for a time. However having too many connections
opens can drain resourses as well. One solution is database
connection pools that maintain a fixed number of connections
open that can be shared. Connection pools are good
compromises between having too many connections open
and having too many slow connects and disconnects.
Database
Connection as a Session Object
A very nice example of JDBC code is found in the book, 'Web
Development with Java Server Pages" by Duane Fields and
company. It achieves a compromise to persisting a database
connection by mating the life of the connection to the life of the
session object.
The bean uses the HTTPSessionBindingListener to signal when
the session is being added or removed and uses the associated
listener methods to open or close the database connection.
This ConnectionBean goes half way to acting as a DataSource
object in that it provides getConnection( ) methods as found in the
DataSource interface and hides away the details of a fixed
connection.
It could be easily written implementing the DataSource interface
in which case it could also be used with JNDI. Finally this code
could easily be modified to accept initialization parameters to
enable it to be
configured for various databases.
Supplemental on Database Connection
We have prepared a supplemental lab showing how we
can include database connectivity with an Eclipse project
which we can look at next.
The following example is provided as a model for the session
based connection talked about above. It would take a bit of
work to set up your database to respond to the queries it
poses. Also you would need to set the connection information
for your own database.
Field, Kolb
& Bayerns Connection Bean // for
reference
// "From Web Development with Java Server Pages",
// D.Fields,
M. Kolb & S. Bayern
package com.taglib.wdjsp.databases;
import java.sql.*;
import javax.servlet.http.*;
public class ConnectionBean implements HttpSessionBindingListener {
private Connection connection;
private Statement statement;
private static final String driver="postgresql.Driver";
private static final String dbURL="jdbc:postgresql://slide/test";
private static final String login="guest";
private static final String password="guest";
public ConnectionBean() {
try {
Class.forName(driver);
connection=DriverManager.getConnection(dbURL,login,password);
statement=connection.createStatement();
}
catch (ClassNotFoundException e) {
System.err.println("ConnectionBean:
driver unavailable");
connection = null;
}
catch (SQLException e) {
System.err.println("ConnectionBean:
driver not loaded");
connection = null;
}
}
public Connection getConnection() {
return connection;
}
public void commit() throws SQLException {
connection.commit();
}
public void rollback() throws SQLException {
connection.rollback();
}
public void setAutoCommit(boolean autoCommit)
throws SQLException {
connection.setAutoCommit(autoCommit );
}
public ResultSet executeQuery(String sql) throws SQLException {
return statement.executeQuery(sql);
}
public int executeUpdate(String sql) throws SQLException {
return statement.executeUpdate(sql);
}
public void valueBound(HttpSessionBindingEvent event) {
System.err.println("ConnectionBean: in the
valueBound method");
try {
if (connection == null ||
connection.isClosed()) {
connection =
DriverManager.getConnection(dbURL,login,password);
statement =
connection.createStatement();
}
}
catch (SQLException e) { connection = null; }
}
public void valueUnbound(HttpSessionBindingEvent event) {
try {
connection.close();
}
catch (SQLException e) { }
finally {
connection = null;
}
}
protected void finalize() {
try {
connection.close();
}
catch (SQLException e) { }
}
}
Field,
Kolb
& Bayerns JSP Page Referencing Connection Bean
// "From Web Development with Java Server Pages", D.Fields,
M. Kolb & S. Bayern
<%@ page import="java.sql.*,com.taglib.wdjsp.databases.*"
errorPage="error.jsp" %>
<jsp:useBean id="connection" class="ConnectionBean"
scope="session"/>
<html>
<body>
<center>
<font size="+2" face="arial"><b>Conference Registration</b></font>
<form action="shuttle.jsp" method="post">
<table border=1 bgcolor="tan" width="50%" align="center">
<tr><td>
<table border="0" bgcolor="white" cellspacing=0 width="100%">
<tr bgcolor="tan">
<th> </th><th>City</th><th>Tickets Remaining</th></tr>
<%
String sql = "SELECT * FROM CONFERENCES";
ResultSet results = connection.executeQuery(sql);
while (results.next()) {
if (results.getInt("seats") > 0) {
%>
<td>
<input type="radio" name="show"
value="<%= results.getString("id") %>">
</td>
<% } else { %>
<td> </td>
<% } %>
<td><%= results.getString("city") %></td>
<td align="center"><%= results.getString("seats") %></td>
</tr>
<% } %>
</table>
</td></tr></table>
<p>
<input type="submit" value="Next (Choose Shuttle)">
</form>
</center>
</body>
</html>
9_JSP_Beans_Ans.html
Self Test
Self
Test With Answers
1) Which of the following would likely be the simplest in nature?
a) Visual GUI JavaBean
b) JSP Data Bean
c) JSP Session Bean
d) Enterprise JavaBean
2) True or False? Simple properties that use boolean types must us the
'is' prefix in it's getter method. True / False
3) Which
of the following is not a property type specified by the JavaBean
specification.
a) simple
b) indexed
c) bound
d)
inhibited
4) Which of the following useBean attributes represents a little
used
alternative way to reference a JavaBean
instance into a Java page.
a) id
b) scope
c) beanName
d)
type
5) Which of the following is not a legal id identifier.
(Note: there are more than one answer)
a ) bill
b) inner$
c) _ref
d)
x2345_12D
6) True or False? The body of useBean tag has characteristics
roughly analogous to a Java class
constructor.
Exercise
1) a) Create 4 JavaBeans one for each Season. ( You can select
any theme you want if you don't feel
'seasonal'!)
b) Define three or four properties for each bean. These should use
different types for practice. May I suggest
two String properties,
an int and a boolean.
c) Write get/set methods for each of them.
d) Use a standalone Java program like the one below to make sure
all your Java code has been formed correctly.
You might prefer
to keep your data beans 'pristine' and use a
separate main program,
something like BeanTester that will instantiate and
test your beans.
class BeanMethodTester{
public static void
main(String[]args){
YourBean yb=new YourBean( );
System.out.println( "Property1: " + yb.getProperty1( ) );
// etc.
}
}
Remember to save the this short class to BeanMethodTester.java and
compile
c:> javac BeanMethodTester.java
run
c:> java BeanMethodTester
Using Eclipse, create a new package. Include this package
declaration at the head of each of your JavaBeans. Save in
Eclipse. It will take care of putting your compiled code in the
correct directory.
f) Create a JSP Page that exposes the properties of these JavaBean
objects using the jsp useBean and jsp:getProperty
tags..
Optional
2) Modifiy the JSP page to include a form that allows you to set the
values of one or more of these beans. Use
setProperty tags to
change the values of the beans. On the same page
output provide
a confirmation note that accesses the newly entered
values via
getProperty tags and outputs them to the page.
Optional
There is enough information in the above supplemental note to make
a database connection with a JDBC driver to a database using a
session bean that encapsulates such a connection. The connection
based on a request could load a RowBean with data that could then
be referenced into a JSP page using the <jsp:useBean> action tag.
The latest release version of mySQL is on the college machines.
The newest driver package is also installed. Alternatively, one could
open using the ODBC:JDBC Driver used in the earlier example.
The Driver class
"com.mysql.jdbc.Driver"
The JDBC url format
jdbc:mysql://[host][,failoverhost...][port]/[database]
//
where default host is 127.0.0.1 and default port is 3306