• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Accessing session or application attributes from within a JavaBean

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 567
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you made the bean a servlet, it would be instantiated with the request and response objects, from which you can obtain the session.
 
Gordon Jenkinson
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Unfortunately that won't solve it as I have multiple beans active at one time witin a page.
Thanks for the response.
Gordon
 
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
I'm a lumberjack and I'm okay, I sleep all night and work all day. Lumberjack ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic