Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating database connections with Class files?  RSS feed

 
Sloan Bowman
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 the JSTL database access tags. See http://courses.coreservlets.com/Course-Materials/11-JSTL.pdf
  • 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
     
    Sloan Bowman
    Ranch Hand
    Posts: 107
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
     
    Consider Paul's rocket mass heater.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!