JSTL and JSP-EL Support


Accessing Databases

The ultimate tool in creating a dynamic Web site is utilizing a database to store the information to be presented to the user. Just like Amazon and a whole host of other sites, you can present dynamic information to your users based on their login. While there are many issues involved with building a dynamic site of the Amazon caliber, the first step is obtaining a connection to a database and retrieving information. Consider the following code:

 <%@ page language="java" import="java.sql.* " %> <html> <body> <%   Class.forName("org.gjt.mm.mysql.Driver");   Connection myConnection DriverManager.getConnection("jdbc:mysql://localhost/mysql");   myStatement = myConnection.createStatement();   ResultSet myRS = myStatement.executeQuery("SELECT * FROM user");   if (myRS != null) {     while (myRS.next()) {       out.println(myRS.getString("username"));     }   }   myStatement.close();   myConnection.close(); %> </body> </html> 

If you are familiar with using JDBC and Java, most of the code in this JSP page will look very familiar. The JDBC methods needed to communicate with a database are found in the java.sql package, which we have imported using the page directive at the start of the code. The Java code within the page pulls in a JDBC driver for the MySQL database and connects to the database. Next, a SQL statement is executed against the database and the information returned displayed to the user. Finally, the connection to the database is closed.

This example is about as simple as it gets. In a production system, you want to pull all of the database code and place it in a JavaBean to reduce the complexity of the JSP page. In fact, all of the database code should be transparent to the JSP code and utilized only through business objects.




Mastering Resin
Mastering Resin
ISBN: 0471431036
EAN: 2147483647
Year: 2002
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net