Table of Contents

Intro

Servlets differ from regular java programs. When a servlet is invoked by the server at the user's request, it doesn't run main(), instead your servlet needs to implement the servlet-api interface and those implemented functions are called instead.

Hello World

Here is an example of a servlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello World!</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello World!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Note that the class extends HttpServlet. This is required so Tomcat knows what functions it can call in the class. When the servlet is requested, Tomcat calls the doGet() function and that function needs to output the HTML or respond in some meaningful way to the client.

The request and response objects are used to get data relating to the original page request and to write data back to the client as a response. In the example above, response's PrintWriter is used to respond to the client with HTML. This dynamically generates HTML on the fly and lets you use the Java language to do interesting things that aren't available in HTML, such as database queries.

JDBC

When you want to connect to the Oracle database, you will likely want to use the JDBC. The Oracle client in the lab has the JDBC drivers for Java JDK 1.5 and JDK 1.6. They are located at /usr/lib/oracle/11.2/client64/lib/ as the files ojdbc5.jar and ojdbc6.jar. There are tutorials for JDBC at http://java.sun.com/products/jdbc/learning/tutorial/index.html and at other places on the internet.

Compiling in the Lab

You can compile your servlets in the CS department lab. The javax.servlet package isn't included with java by default, but Tomcat comes with servlet-api.jar which provides this package. You'll need to include this .jar in your classpath when you compile. You can download servlet-api.jar below.

You can copy the Oracle JDBC drivers to your application and use those to connect to the Oracle server.

Downloads

servlet-api.jar ojdbc5.jar ojdbc6.jar