I was wondering if it was possible to create a database conection use Classes in Java and JSP. I do this when I use PHP to prevent me from having to type out the connection strings over and over again. On each page that I use a query. Has anybody done this before? Class Example: public class Database { // Globals Object db; public Database(){}
public void setDriver(String driver) { Class.forName(driver); } // end setDriver public void setConnect(String uri,String user, String pass) { this.db = Connection db = DriverManager.getConnection(uri, user, pass); } // end setConnect() } // end class Then call it from jsp <jsp:useBean id="database" class"bean.Database" scope="page"/> database.setDriver("org.postgresql.Driver"); database.setConnect("bla", "user", "pass");
etc.. etc.. Thanks for the help.
Marty Hall
Author
Ranch Hand
Joined: Jan 02, 2003
Posts: 111
posted
0
I was wondering if it was possible to create a database conection use Classes in Java and JSP. I do this when I use PHP to prevent me from having to type out the connection strings over and over again. On each page that I use a query. ... Example with a class that does some JDBC stuff and a JSP page that calls it.
Are you asking "Instead of doing JDBC operations in a JSP page, can I create a helper class that does some database operations and then call that helper class from JSP?" If so, then the answer is "Yes, of course!" You certainly should not put the JDBC calls directly in your JSP page. Calling a helper class is better. But, there are some even better options than that:
Use MVC. Start with a servlet. Have it do the database stuff. Have it store the results in a bean. Forward to a JSP page via RequestDispatcher. Have the JSP page display the results only. (Possibly using the JSTL looping tags).
I prefer the second option from this list, but certainly your idea is much better than putting all the JDBC code right in the JSP page where it would be hard to debug, hard to test, and impossible to reuse in other pages. Cheers- - Marty
Java training and consulting<br /><a href="http://www.coreservlets.com/" target="_blank" rel="nofollow">http://www.coreservlets.com/</a>
Sloan Bowman
Ranch Hand
Joined: Jan 21, 2003
Posts: 107
posted
0
Thank you very much this is exactly what I was looking for. I'll have to do some research and get things rolling. Again thanks! --Sloan
subject: Creating database connections with Class files?