[thelist] Need help building a simple JSP/MySQL webapp

Hassan Schroeder hassan at webtuitive.com
Tue Jan 31 10:00:44 CST 2006


Rick den Haan wrote (not in this order):

> I might be thinking too much along PHP's mindset here...

Yeah. Not a criticism, but that's obvious from the sample code,
and for the sake of future good practice, something to get over :-)

> My MySQL database is called "jsp_test", in which there's a table called
> "customers" which has four columns for "id", "name", "address" and "phone".
> I want a JSP page that ends up listing my customers, ordered by id. I.e.:

> For JSP, I have absolutely no clue where to go from what I have now. I have
> an excellent Java guidebook (Y. Daniel Liang's "Introduction to Java
> Programming", 5th Edition), which told me to go and download a MySQL JDBC
> connector, which I did, but I don't know where to place it so that Tomcat
> will be able to connect to it, nor what JSP code I have to use to connect to
> it once I get it there.

I don't know that I'd call a book with sample code like that given
"excellent"; it's missing the whole point of JSP/Servlets and the
MVC design pattern (apparently).

On the other hand, correcting it will require writing another book,
which I don't have time to do right now. :-)  So, to your immediate
connect-to-DB problem.

1) you want to use Tomcat's built-in connection pooling; put the
   Connector/J jar in $CATALINA_HOME/common/lib, and follow the
   directions here:
   <http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html>
   :: to configure your server.xml and deployment descriptor (the
   web.xml under your app's WEB-INF directory).

2) read the servlet spec; a lot of it won't make sense right now
   but it's important, and it'll grow on you :-)

3) join the tomcat-users mailing list; you'll learn a lot about
   JSP/Servlets, not just Tomcat-specific stuff.

In practice, you never have DB access in a JSP; it's part of the
presentation (View) layer, not the Model or Controller.

So you're going to want to start thinking in terms of Objects. For
your example, you'd create a Customer class that encapsulates the
fields defining a "customer" and accesses them from your DB. Once
you've got that, you can simply reference it from any page, rather
than embedding SQL calls throughout the site. Or to use a popular
acronym: DRY -- Don't Repeat Yourself. :-)

HTH! And feel free to ask for clarification of any of the above;
I'm only on my first cup of coffee...
-- 
Hassan Schroeder ----------------------------- hassan at webtuitive.com
Webtuitive Design ===  (+1) 408-938-0567   === http://webtuitive.com

                          dream.  code.





More information about the thelist mailing list