Posted by enquirer (enquirer), 6 March 2004
Can you give me an example of all the pieces of code I'll need to write a JSP that looks something up in a database?
Posted by admin (Graham Ellis), 6 March 2004
You'll need:
a) A form in which to enter any information needed to define your query
b) Your JSP page to perform the query and report
c) A Java bean to do the "real work" behind the JSP page
The form
Code:<head> <title>ISBN lookup!</title> </head> <body> <h1>Find an author from an ISBN number</h1> Please enter the ISBN number of a book in the Well House Consultants library and we'll tell you the name of (one of) the Authors <br> <form action=getauthor.jsp>Enter ISBN <input name="isbn" /><br /> <input type="submit" /></form> </body> |
|
The JSP page (getauthor.jsp in the same directory as the form)
Code:<html> <head> <title>Author of book from ISBN number</title> </head> <body> <h1> Result page</h1> <jsp:useBean id="fred" class="boox.Book" /> <jsp:setProperty name="fred" property="*" /> <% if (fred.getAuthor().equals("numerous")) { %> That is not an ISBN number on our database<br> <% } else { %> Author is <jsp:getProperty name="fred" property="author" /><br> <% } %> Done! </body> |
|
The Java bean (in WEB-INF/classes/boox, compiled to .class)
Code:package boox; import java.sql.*; public class Book { String Isbn; public Book () { Isbn = null; } public void setIsbn(String val) { Isbn = val; } public String getAuthor() { String Wanted = "numerous"; if (Isbn == null) return "Not set"; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Connection books = DriverManager.getConnection ("jdbc:mysql://192.168.200.188/wellho?user=trainee&password=abc123"); Statement s = books.createStatement(); ResultSet r = s.executeQuery ("Select authorfull from books where isbn = \""+Isbn+"\""); while (r.next()) { Wanted = r.getString("authorfull"); } } catch (Exception e) { return e.toString(); } return Wanted; } public static void main (String [] args) { Book Desk = new Book(); Desk.setIsbn("0-596-00283-1"); String By = Desk.getAuthor(); System.out.println(By); }
} |
|
This is cut and pasted from a training server, and has been tested. In a live application you would add better feedback, error testing and exception handling as a minimum. You would also use a better password on your database!
This page is a thread posted to the opentalk forum
at
www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow
this link.