JSP Components
 
Introduction
 
A JavaServer Pages (JSP) component may use a JavaBeans component as a proxy to access an enterprise bean.
The following diagram illustrates how these components work together:
 
JSP Client of an Enterprise Bean
 
The Below sections that follow show how to create a J2EE application with the following elements:
 
.JSP client:
<html>
<jsp:useBean id="accountBean" scope="session" class="AccountBean" />
<jsp:setProperty name="accountBean" property="*" />
<%! String status; %>
<% status = accountBean.processRequest(); %>
<html>

<head>
<title>Account JSP</title>
</head>
<body background="back.gif">
<font size = 5 color="#CC0000">
<h1><b><center>Account JSP Example</center></b></h1>
<hr>
<br>

<form method=POST action=Account.jsp>
<BR>
<br>Account ID <INPUT type=text name="id" size="8" value="<jsp:getProperty name="accountBean" property="id" />" >
Balance <INPUT type=text name="balance" size="8" value="<jsp:getProperty name="accountBean" property="balance" />" ><br>
First Name <INPUT type=text name="firstName" size="8" value="<jsp:getProperty name="accountBean" property="firstName" />">
Last Name <INPUT type=text name="lastName" "size=8" Value="<jsp:getProperty name="accountBean" property="lastName" />" ><br> <br>
<h2><b>Action :</b></h2>
<INPUT type="radio" name="action" value="create">Create
<INPUT type="radio" name="action" value="find">Find
<INPUT type="radio" name="action" value="debit">Debit
<INPUT type="radio" name="action" value="credit">Credit
<br>

<br>Amount <INPUT type=text name="amount"><br>
<INPUT type=submit name="submit" value="Submit">
</form>
</FONT>
</body>
</html>

<hr>
<h3><b>Status :</b></h3> <%= status %>
</html>
 
.JavaBeans component:
 
import java.util.*;
import java.io.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class AccountBean {
private String action;
private String id;
private String firstName;
private String lastName;
private double balance;
private double amount;

private AccountHome accountHome;
private Account account;

public AccountBean() {
try {
Context ic = new InitialContext();

java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account");

accountHome = (AccountHome) PortableRemoteObject.narrow(objref, AccountHome.class);

System.out.println("obtained accountHome object");

} catch (Exception re) {
System.err.println ("Couldn't locate Account Home");
re.printStackTrace();
}
reset();

}
public String processRequest() {
String message = "";
System.out.println("Process request called ");
System.out.println(this);
try {
if( action.equals("create") ) {
account =
accountHome.create(id, firstName, lastName, balance);
message = "Created account '" + id + "'";

}
else if( action.equals("debit") ) {
account = accountHome.findByPrimaryKey(id);
account.debit(amount);
loadFromEJB();
message = "Debited account '" + id + "' by $" + amount;
}
else if( action.equals("credit") ) {
account = accountHome.findByPrimaryKey(id);
account.credit(amount);
loadFromEJB();
message = "Credited account '" + id + "' by $" + amount;
}
else if( action.equals("find") ) {
account = accountHome.findByPrimaryKey(id);
loadFromEJB();
message = "Found account '" + id;

}
} // try
catch (Exception e) {
message = e.toString();
}
return message;
}
public String getAction() {
System.out.println("Getting action");
return action;
}
public void setAction(String a) {
System.out.println("Setting action : " + a);
action = a;
}
public String getId() {
System.out.println("Getting id");
return id;
}
public void setId(String i) {
System.out.println("Setting id : " + i);
id = i;
}
public String getFirstName() {
System.out.println("Getting firstName");
return firstName;
}
public void setFirstName(String f) {
System.out.println("Setting first name : " + f);
firstName = f;
}

public String getLastName() {
System.out.println("Getting lastName");
return lastName;
}

public void setLastName(String l) {
System.out.println("Setting last name : " + l);
lastName = l;
}

public double getBalance() {
System.out.println("Getting balance");
return balance;
}

public void setBalance(double b) {
System.out.println("Setting balance : " + b);
balance = b;
}

public double getAmount() {
System.out.println("Getting amount");
return amount;
}

public void setAmount(double a) {
System.out.println("Setting amount : " + a);
amount = a;
}

private void reset() {
System.out.println("Calling reset()");
final String emptyString = "";
final double zero = 0.0;

setAction(emptyString);
setId(emptyString);
setFirstName(emptyString);
setLastName(emptyString);
setBalance(zero);
setAmount(zero);
}

private void loadFromEJB() {
System.out.println("Calling loadFromEJB()");
try {
setFirstName(account.getFirstName());
setLastName(account.getLastName());
setBalance(account.getBalance());
} catch (Exception re) {
System.err.println ("Failed to load AccountBean from AccountEJB.");
re.printStackTrace();v }
}

public String toString() {
StringBuffer output = new StringBuffer();

output.append("Action : " + action);
output.append( " Id : " + id);
output.append( " first name : " + firstName);
output.append( " last name : " + lastName);
output.append( " balance : " + balance);
output.append( " amount : " + amount);
return output.toString();
}
}
 
.Entity bean:
 
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;

public class AccountEJB implements EntityBean {

private String id;
private String firstName;
private String lastName;
private double balance;
private EntityContext context;
private Connection con;
private String dbName = "java:comp/env/jdbc/AccountDB";

public void debit(double amount)
throws InsufficientBalanceException {

if (balance - amount < 0) {
throw new InsufficientBalanceException();
}
balance -= amount;
}

public void credit(double amount) {

balance += amount;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {

return lastName;
}

public double getBalance() {

return balance;
}

public String ejbCreate(String id, String firstName, String lastName, double balance)
throws CreateException {

if (balance < 0.00) {
throw new CreateException
("A negative initial balance is not allowed.");
}

try {
insertRow(id, firstName, lastName, balance);
} catch (Exception ex) {
throw new EJBException("ejbCreate: " + ex.getMessage());
}

this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;

return id;
}

public String ejbFindByPrimaryKey(String primaryKey)
throws FinderException {

boolean result;
try {
result = selectByPrimaryKey(primaryKey);
} catch (Exception ex) {
throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
}
if (result) {
return primaryKey;
}
else {
throw new ObjectNotFoundException
("Row for id " + primaryKey + " not found.");
}
}

public Collection ejbFindByLastName(String lastName) throws FinderException {

Collection result;

try {
result = selectByLastName(lastName);
} catch (Exception ex) {
throw new EJBException("ejbFindByLastName " + ex.getMessage());

}

if (result.isEmpty()) {
throw new ObjectNotFoundException("No rows found.");
}
else {
return result;
}
}

public Collection ejbFindInRange(double low, double high)
throws FinderException {

Collection result;

try {
result = selectInRange(low, high);

} catch (Exception ex) {
throw new EJBException("ejbFindInRange: " + ex.getMessage());
}
if (result.isEmpty()) {
throw new ObjectNotFoundException("No rows found.");
}
else {
return result;
}
}

public void ejbRemove() {

try {
deleteRow(id);
} catch (Exception ex) {
throw new EJBException("ejbRemove: " + ex.getMessage());
}
}

public void setEntityContext(EntityContext context) {

this.context = context;
try {
makeConnection();
} catch (Exception ex) {
throw new EJBException("Unable to connect to database. " +
ex.getMessage());
}
}

public void unsetEntityContext() {


try {
con.close();
} catch (SQLException ex) {
throw new EJBException("unsetEntityContext: " + ex.getMessage());
}
}

public void ejbActivate() {

id = (String)context.getPrimaryKey();
}
public void ejbPassivate() {

id = null;
}
public void ejbLoad() {

try {
loadRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: " + ex.getMessage());
}
}

public void ejbStore() {

try {
storeRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: " +
ex.getMessage());
}
}

public void ejbPostCreate(String id, String firstName,
String lastName, double balance)
{ }

/*********************** Database Routines *************************/

private void makeConnection() throws NamingException, SQLException {

InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(dbName);
con = ds.getConnection();
}

private void insertRow (String id, String firstName, String lastName,
double balance) throws SQLException {

String insertStatement = "insert into account values ( ? , ? , ? , ? )";
PreparedStatement prepStmt =
con.prepareStatement(insertStatement);

prepStmt.setString(1, id);
prepStmt.setString(2, firstName);
prepStmt.setString(3, lastName);
prepStmt.setDouble(4, balance);

prepStmt.executeUpdate();
prepStmt.close();
}

private void deleteRow(String id) throws SQLException {

String deleteStatement = "delete from account where id = ? ";
PreparedStatement prepStmt = con.prepareStatement(deleteStatement);

prepStmt.setString(1, id);
prepStmt.executeUpdate();
prepStmt.close();
}

private boolean selectByPrimaryKey(String primaryKey)
throws SQLException {

String selectStatement =
"select id " +
"from account where id = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setString(1, primaryKey);

ResultSet rs = prepStmt.executeQuery();
boolean result = rs.next();
prepStmt.close();
return result;
}

private Collection selectByLastName(String lastName)
throws SQLException {

String selectStatement =
"select id " +
"from account where lastname = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);

prepStmt.setString(1, lastName);
ResultSet rs = prepStmt.executeQuery();
ArrayList a = new ArrayList();

while (rs.next()) {
String id = rs.getString(1);
a.add(id);
}

prepStmt.close();
return a;
}

private Collection selectInRange(double low, double high)
throws SQLException {

String selectStatement =
"select id from account " +
"where balance between ? and ?";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setDouble(1, low);
prepStmt.setDouble(2, high);
ResultSet rs = prepStmt.executeQuery();
ArrayList a = new ArrayList();

while (rs.next()) {
String id = rs.getString(1);
a.add(id);
}

prepStmt.close();
return a;
}

private void loadRow() throws SQLException {

String selectStatement =
"select firstname, lastname, balance " +
"from account where id = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);

prepStmt.setString(1, this.id);

ResultSet rs = prepStmt.executeQuery();

if (rs.next()) {
this.firstName = rs.getString(1);
this.lastName = rs.getString(2);
this.balance = rs.getDouble(3);
prepStmt.close();
}
else {
prepStmt.close();
throw new NoSuchEntityException("Row for id " + id +
" not found in database.");
}
}

private void storeRow() throws SQLException {
String updateStatement =
"update account set firstname = ? ," +
"lastname = ? , balance = ? " +
"where id = ?";
PreparedStatement prepStmt =
con.prepareStatement(updateStatement);
prepStmt.setString(1, firstName);
prepStmt.setString(2, lastName);
prepStmt.setDouble(3, balance);
prepStmt.setString(4, id);
int rowCount = prepStmt.executeUpdate();
prepStmt.close();

if (rowCount == 0) {
throw new EJBException("Storing row for id " + id + " failed.");
}
}

} // AccountEJB
 
The Account.jsp and AccountBean.java files are in the
doc/guides/ejb/examples/jsptobean directory.
 
The AccountEJB.java source code is in the
doc/guides/ejb/examples/account directory.