Getting Apache Tomcat 5.5 and PostgreSQL 8.1 to Work Together
(Tutorial) (3/3)
Date: 2006_0109
Installation Environment: Mac OS 10.4
Installation Packages: Apache Tomcat 5.5.12, PostgreSQL 8.1
Contributor: Orton Huang [/oth]
Step 5. Writing Example JSP's and Servlet's
In this section, I'll go over how to write basic JSP's and Servlet's
that can communicate with the database. To begin with, I'll avoid all
the packaging with ANT and WAR's (Web Archives) and start simple to
get you started.
5.1 Setup and Configuration
In your Tomcat installation (for me, $CATALINA_HOME is
/usr/local/apache-tomcat-5.5.12), web applications go in the directory
$CATALINA_HOME/webapps. So, we'll write a basic JSP, a basic Servlet
and then a JSP that accesses the database and then a Servlet that
accesses the database.
So let's start by creating the necessary directories in
$CATALINA_HOME/webapps. The webapp's name will be "testapp"
~> cd /usr/local/apache-tomcat-5.5.12/webapps
webapps> mkdir testapp
webapps> mkdir testapp/WEB-INF
webapps> mkdir testapp/WEB-INF/classes
webapps> mkdir testapp/WEB-INF/lib
5.2 web.xml
Then, we need a configuration file (web.xml) for testapp. You
can copy one from one of the other webapp directories.
~> cp
/usr/local/apache-tomcat-5.5.12/webapps/tomcat-docs/WEB-INF/web.xml
/usr/local/apache-tomcat-5.5.12/webapps/testapp/WEB-INF/
You'll have to modify the web.xml file. Here's some basic stuff:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test Web Application</display-name>
<description>
Test Application
</description>
<context-param>
<param-name>webmaster</param-name>
<param-value>test@test.com</param-value>
</context-param>
</web-app>
5.3 Test JSP for Time Example
So, our first goal is to write a simple JSP and drop it into the
testapp directory. This simple JSP will simply show the current
time. Here's the code for a JSP that will show the time:
<HTML>
<HEAD>
<TITLE>JSP Sample: Time</TITLE>
</HEAD>
<BODY>
<H1>Current Time (JSP)</H1>
Time: <%= new java.util.Date() %>
</BODY>
</HTML>
You can take this code, place it in a file called time.jsp and drop it
into your $CATALINA_HOME/webapps/testapp directory.
Next, make sure your local Tomcat is running by going to:
http://localhost:8080
Then, you can test out time.jsp by going to:
http://localhost:8080/testapp/time.jsp
5.4 Test Servlet for Time Example
Alright! Now that we have a simple JSP, let's make it into a
Servlet. To do this, we'll have to modify our web.xml which is
in $CATALINA_HOME/webapps/testapp/WEB-INF. Let's take a look at
the new web.xml file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test Web Application</display-name>
<description>
Test Application
</description>
<context-param>
<param-name>webmaster</param-name>
<param-value>test@test.com</param-value>
</context-param>
<servlet>
<servlet-name>TimeTest</servlet-name>
<description>
Time Test Servlet
</description>
<servlet-class>TimeTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TimeTest</servlet-name>
<url-pattern>/TimeTest</url-pattern>
</servlet-mapping>
</web-app>
As you can see, two new elements <servlet> and
<servlet-mapping> have shown
up. <servlet-mapping>, as you can guess, maps the Java
Servlet TimeTest.class to the url testapp/TimeTest
So, what does the TimeTest.class look like? Here's the source
code.
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Test Time Servlet
*/
public class TimeTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String newTime = (new Date()).toString();
out.println("<html>");
out.println("<head>");
out.println("<title>Time Test Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Current Time (Servlet)</h1>");
out.println(newTime);
out.println("</body>");
out.println("</html>");
}
}
Create a file TimeTest.java in
$CATALINA_HOME/webapps/testapp/WEB-INF/classes and copy the
above source into it. Now, we have to compile the file. From here,
{testapp} will refer to
$CATALINA_HOME/webapps/testapp/.
Go to
{testapp}/WEB-INF/classes. To compile the code, you can type:
javac TimeTest.java
You have to make sure that a couple of things are in your
CLASSPATH. The things in my classpath are:
.
/usr/local/apache-tomcat-5.5.12/common/lib/servlet-api.jar
/usr/local/apache-tomcat-5.5.12/common/lib/postgresql-8.1-404.jdbc3.jar
After the code is compiled, you'll have a TimeTest.class file
in your {testapp}/WEB-INF/classes directory. Now, you can see
your handiwork. In a browser, go to:
http://localhost:8080/testapp/TimeTest
And you'll see your Servlet displaying the current time now.
Next, we'll go on to write the JSP that will communicate with the
database. Then before we go on to write the Servlet that does the same
thing, we'll go through the Eclipse installation.
5.5 Test JSP for Database Example
First, we want to make sure that we have all the right roles. The
test_table is in the database testdb. So we want to make
sure that the user temp_user can access it.
~> psql testdb
testdb=# create group testdb;
testdb=# alter group testdb add user temp_user;
That will create the group testdb and add the temp_user
to that group. This now allows temp_user to log into the
testdb database.
Now that temp_user can access the testdb database, he
has to be able to access and modify the table test_table where
the data we entered earlier is. We created test_table using the
postgres account earlier. So now we have to log into
testdb with that account to give temp_user the
appropriate privileges.
~> psql testdb postgres
testdb=# GRANT ALL ON test_table TO temp_user;
Now, we're ready to to write our JSP that will access data in
test_table and print it to the screen.
Here is the example JSP. This JSP opens the connection and logs
in. Then it selects all the data from test_table and returns it
in a ResultSet. Using the Metadata in the ResultSet, it determines the
number of columns and the names of the columns to print them out. Then
it iterates through all the rows in the ResultSet and adds them to the
table.
<head>
<title>Simple Database Example (JSP)</title>
</head>
<body bgcolor=#FFFFFF>
<h2>
Simple Database JSP Example
</h2>
<%@ page import="java.sql.*" %>
<%!
String jdbcDriver = "org.postgresql.Driver";
String jdbcURL = "jdbc:postgresql:testdb";
String user = "temp_user";
String password = "temp";
%>
<%
try {
Class.forName(jdbcDriver).newInstance();
Connection conn = DriverManager.getConnection(jdbcURL, user,
password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from test_table");
ResultSetMetaData rsmd = rs.getMetaData();
int numOfCols = rsmd.getColumnCount();
out.print("<center>");
out.print("<h3>Data in table: test_table</h3>");
out.print("<table width=400 cellspacing=5
cellpadding=5><tr>");
for ( int i=1; i<numOfCols+1; i++ ) {
out.print("<td><b>" + rsmd.getColumnName(i) +
"</b></td>");
}
out.print("</tr>");
while (rs.next()) {
out.print("<tr>");
for ( int i=1; i<numOfCols+1; i++ ) {
out.print("<td>" + rs.getString(i) + "</td>");
}
out.print("</tr>");
}
out.print("</table>");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
out.print("<p><pre>" + e.toString() + "</pre>");
}
%>
<p>
</body>
</html>
This should produce a page that looks something like this.
Next, we'll look at installing Eclipse and getting it to work in this
environment.
|