Displaying Records from the Database with Java Servlets. Overview : In this article I'll explain each step you need to know to display records from the database using Servlets. The steps for displaying records in JSP pages and Java Beans are almost the same. We will first build a small example Microsoft Access database, create a DSN for it and using JDBC ( Java Database Connectivity ) driver connect with it and display the records from a given table. Since 80% of your time developing applications will be spent on interacting with databases, you should pay utmost importance to this article. Access Database : You can use any database of your choice but for this article I will stick with Microsoft Access database on a Windows platform. The steps for creating such a database and assigning a DSN have already been explained in detail in an earlier article, you should consult that article for details. I will only briefly mention it here. Create a new Access database with the name of 'odbc_exmp.mdb' and create a table 'Names' containing three fields 'ID', 'first_name' and 'last_name' where 'ID' is the primary key : Go to the control panel and create a new DSN ( Data Source Name ) 'odbc_exmp' for it and point it to the path of your database on your computer. Populate the 'Names' table with any values like the following so that we can display the records later : We are finished with the database. Move on to the next page where we create our Java Servlet to display these records on the user screen. DisplayServlet : Create a new DisplayServlet.java file in the /APP_NAME/WEB-INF/classes/com/stardeveloper/servlets/db/ folder. Note /APP_NAME/ is the path of your application within your application server, in Tomcat 4.0 /APP_NAME/ will be /CATALINA_HOME/webapps/star/ where 'star' is the name of the application. Copy and paste the following code into DisplayServlet.java file and compile it :
|