Getting Apache Tomcat 5.5 and PostgreSQL 8.1 to Work Together (Tutorial) (4/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. Installing and Configuring Eclipse

Eclipese is a development platform. You can find more about it at their homepage: www.eclipse.org.

You can download it here. The version I downloaded was "eclipse-SDK-3.1.1-macosx-carbon.tar.gz".

The installation of Eclipse is really simple. Simply unzip the downloaded file and it's ready to run. THe first time you run it, you'll have to set up a home directory for your code.

Next, we'll have to download the Sysdeo Tomcat plugin for Eclipse. You can download that plugin at Sysdeo's website here. After you've downloaded it, place it in the {eclipse}/plugin directory for Eclipse.

Now, we're ready to start Eclipse. You can do that by going to the {eclipse} installation directory and clicking on the "Eclipse" file. After you're started Eclipse, you'll have to set some preferences.

Go to Eclipse->Preferences. Then, in the left hand menu, go to Java->Installed JREs. Make sure that the JVM 1.5.0 (Mac OS X Default) is set.

Now, we'll have to set the Tomcat Home variable. In the same left hand menu, you should see an item for "Tomcat". If it is not there, trying restarting eclipse from the command line with this:

java -jar startup.jar -clean
Now, select Tomcat from the menu on the left hand. Click on "Version 5.x" and browse to the "Tomcat home" location. For our installation, it was /usr/local/apache-tomcat-5.5.12.

5.1 Creating a Project using Tomcat and Eclipse

Click on File->New->Project. Then, click on Java->Tomcat Project. Then, click "Next".

We'll title the project "TomcatTest" and use the default for the directory for the project.

Then click "Finish".

When you go to your workbench (upper-left hand button), You'll see your new project in the Package Explorer window. Let's put in our original JSP to test that our setup is working correctly.

Start by clicking on New -> File. We'll title it time.jsp like we did earlier. Now, we can copy the code over into that file. Here's a copy of it for your convenience.


<HTML>
  <HEAD>
    <TITLE>JSP Sample: Time</TITLE>
  </HEAD>
<BODY>

<H1>Current Time (Tomcat, JSP)</H1>

Time: <%= new java.util.Date() %>

</BODY>
</HTML>

Note: Make sure you stop your previous Tomcat server. We're going to start it from Eclipse.

Save the file, and let's start the Tomcat Server! Sysdeo added a Tomcat server button to your toolbar. Click on that to start the server.

After it's started up, you can reach it by entering http://localhost:8080/TomcatTest/time.jsp into your browser.

5.2 Basic Servlet using Eclipse

Now, let's write the same basic Servlet we wrote before but do it in Eclipse. This process is fairly simple and you only have to create the same two classes. We'll call the servlet class TestTCServlet.

In Eclipse, create a new Java class File -> New -> Class and call it TestTCServlet.java and set its Superclass to be HttpServlet. Then, you can paste in this code:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;

public class TestTCServlet 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 using Tomcat</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Current Time (Servlet made through Tomcat)</h1>");
    out.println(newTime);
    out.println("</body>");
    out.println("</html>");
    }
}   

Now, we'll have to create the web.xml file and place the appropriate contents into it.

In the Package Explorer tree, right-click on WEB-INF and then click New->File and name it web.xml. Its contents should be:

<?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 Tomcat Servlet</display-name>
  <description>
    Test Tomcat Servlet
  </description>

  <context-param>
      <param-name>webmaster</param-name>
      <param-value>test@test.com</param-value>
  </context-param>

  <servlet>
    <servlet-name>TestTCServlet</servlet-name>
      <description>
        Time Test Servlet
      </description>
    <servlet-class>TestTCServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>TestTCServlet</servlet-name>
    <url-pattern>/TestTCServlet</url-pattern>
  </servlet-mapping>

</web-app> 
Now, you're ready to run it. After you've started or restarted your Tomcat, you can go to:
http://localhost:8080/TomcatTest/TestTCServlet

5.3 Basic Database Servlet Using Eclipse

Now, we'd like to do the same Database example we had before but as a Servlet using Eclipse. So, create a new Java file and let's call it TestDBServlet. Here's the code that would go in for it:
import java.io.*;

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;

public class TestDBServlet extends HttpServlet {

    Connection conn;
    private ServletConfig config;

    public void init() throws ServletException {
       this.config = config;
    }      

    public void doGet(HttpServletRequest request, HttpServletResponse
        response) throws IOException, ServletException {
	
	response.setContentType("text/html");
	PrintWriter out = response.getWriter();

	try {
	    Class.forName("org.postgresql.Driver");
	    conn = DriverManager.getConnection("jdbc:postgresql:testdb",
	        "temp_user","temp");
	    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 (SQLException e) {
	    throw new ServletException(e);
	} catch (ClassNotFoundException e) {
	    System.out.println( "ClassNotFoundException" );
	} finally {
	    try {
	        if (conn != null)
		conn.close();
	    } catch (SQLException e) {
	        System.out.println( "SQLException" );
	    }
	}
    }    
}

Finally, add the appropriate xml into web.xml

  <servlet>
    <servlet-name>TestDBServlet</servlet-name>
      <description>
        Time Test Servlet
      </description>
    <servlet-class>TestDBServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>TestDBServlet</servlet-name>
    <url-pattern>/TestDBServlet</url-pattern>
  </servlet-mapping>


Prev (JSPs/Servlets) | Home