wood burning stoves 2.0*
The moose likes JSP and the fly likes Accessing session or application attributes from within a JavaBean Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Accessing session or application attributes from within a JavaBean" Watch "Accessing session or application attributes from within a JavaBean" New topic
Author

Accessing session or application attributes from within a JavaBean

Gordon Jenkinson
Greenhorn

Joined: Feb 03, 2002
Posts: 14
Hi,
I'm relatively new to JSP and Java and have a question which has been bugging me and I can't seem to find a good solution.
I use a javabean to store customer information entered on a JSP page. This information is then validated and stored in a database. Currently I'm using a session level bean instantiated in the JSP to manage the database connection. This means (or does it, this is my question) that I have to pass the session as a parameter to the save() method of the Customer bean so that it can then get the database connection.
Is there a way for the bean to get it's session context without passing it to a method.
My code currently looks something like this.
JSP Page ***************************
<jsp:useBean id="customer" scope="page" class="com.mwp.CustomerDetails" >
<jsp:setProperty name="customer" property="*"/>
</jsp:useBean>
<jsp:useBean id="dbm" scope="page" class="com.mwp.DatabaseManager" >
</jsp:useBean>
<%
String display;
String message = null;
HashMap v = customer.validate(dbm.getConnection(session));
session.removeAttribute("validation");
if ( v.isEmpty() ) {
try {
customer.save(dbm.getConnection(session));
session.setAttribute("message",message);
String custId = customer.getCustomerID();
session.setAttribute("custId",custId);
session.removeAttribute("customer");
display="customerAdded.jsp";
} catch (SQLException e) {
session.setAttribute("message",e.getMessage());
session.setAttribute("customer",customer);
display="customerEdit.jsp";
}
} else {
message = "Errors in form see below for details";
session.setAttribute("message",message);
session.setAttribute("customer",customer);
session.setAttribute("validation",v);
display = "customerEdit.jsp";
}
%>
<jsp:forward page="<%= display %>"/>
DatabaseManager Bean code *************************
public class DatabaseManager
{
String driverName;
String dbURL;
String dbUser;
String dbPassword;
String session;
public DatabaseManager()
{
// Default database parameters here.
driverName = "oracle.jdbc.driver.OracleDriver";
dbURL = "jdbc racle:thin:@192.168.0.4:1521 ELLXP8I";
dbUser = "mwp";
dbPassword = "mwp";
}
public String getDriverName()
{
return driverName;
}
public void setDriverName(String newDriverName)
{
driverName = newDriverName;
}
public String getDbURL()
{
return dbURL;
}
public void setDbURL(String newDbURL)
{
dbURL = newDbURL;
}
public String getDbUser()
{
return dbUser;
}
public void setDbUser(String newDbUser)
{
dbUser = newDbUser;
}
public String getDbPassword()
{
return dbPassword;
}
public void setDbPassword(String newDbPassword)
{
dbPassword = newDbPassword;
}
public String getSession()
{
return session;
}
public void setSession(String newSession)
{
session = newSession;
}
public Connection getConnection(HttpSession session)
throws Exception, SQLException
{
Connection conn = (Connection)session.getAttribute("conn");
if ( conn == null ) {
Class.forName(driverName);
conn = DriverManager.getConnection(dbURL,dbUser,dbPassword);
session.setAttribute("conn", conn);
}
return conn;
}
}
Customner Java bean save method. *************************
public void save(Connection conn) throws SQLException
{
String sql = null;
PreparedStatement insertStmt;
conn.setAutoCommit(false);

if (getUpdateStatus().equals("NEW")) { // It's a new Customer.
sql = "INSERT INTO CUSTOMER"
+ "( CustomerID, UserID, Password, BusinessName, FirstName, Surname, MiddleName, Salutation, Sex, DOB, DefaultAddressID, CustomerTypeID)"
+ " VALUES (?,?,?,?,?,?,?,?,?,TO_DATE(?,'DDMMYYYY'),?,1 )";

try {

insertStmt = conn.prepareStatement(sql);

// Get sequences
customerID = OracleSequence.getNextVal(conn, "CUSTOMER_SEQ" );
mailingAddressID = OracleSequence.getNextVal(conn, "ADDRESS_SEQ" );
billingAddressID = OracleSequence.getNextVal(conn, "ADDRESS_SEQ" );

...
}
Any ideas would be appreciated.
Thanks


Gordon Jenkinson
Adam Hardy
Ranch Hand

Joined: Oct 09, 2001
Posts: 565
If you made the bean a servlet, it would be instantiated with the request and response objects, from which you can obtain the session.


I have seen things you people would not believe, attack ships on fire off the shoulder of Orion, c-beams sparkling in the dark near the Tennhauser Gate. All these moments will be lost in time, like tears in the rain.
Gordon Jenkinson
Greenhorn

Joined: Feb 03, 2002
Posts: 14
Unfortunately that won't solve it as I have multiple beans active at one time witin a page.
Thanks for the response.
Gordon
Graeme Brown
Ranch Hand

Joined: Oct 13, 2000
Posts: 193
I think you have an architecture problem.
Customers are data objects, they don't need to know about connections or where they are saved, or even if they are saved.
DatabaseManager knows about connections and how to save objects. So create a method in DatabaseManager
public void saveCustomer(Customer aCustomer)
and get rid of the save method in Customer.

Also, attaching a Connection to each Session means a one to one mapping between clients and database sessions. This isn't a scalable solution. Manage the connections in the DatabaseManager and share them between clients, ideally by using a JDBC2 DataSource.
[ February 04, 2002: Message edited by: Graeme Brown ]
Gordon Jenkinson
Greenhorn

Joined: Feb 03, 2002
Posts: 14
Thanks Graham, I suppose what I'm trying to do is model my application so that I can use these objects independently of a database. Your solution looks like a good alternative but makes the DatabaseManager more than it should be. Is this your standard approach to JSP and database development. Does your database manager not get very complex as the number of objects you need to save gets large?
I suppose either way I need to pass something between the two. I Either pass the object to the DatabaseManager or I pass a connection to the JavaBean.
On the session level db connection your point is well taken. I plan to modify the DatabaseManager later to work as an application level connection pool. This method allows me to start out with the basic objects in place and implement connection pooling later.
It's beginning to look like the answer to my question is no.
Thanks again for another alternative. I'm not sold on it yet as I like the idea of keepeing the save and retrive logic in the bean. It's seems closer to the idea of an Entity EJB with bean managed persistence. Maybe I should make the leap to EJBs instead.
Cheers

Gordon
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Accessing session or application attributes from within a JavaBean
 
Similar Threads
Get Database connection
Problem while inserting data into MS SQL table
Help with servlets
isNew() method
Problems with encodeURL