Lunanbay Servlets HowTo

Setup

You need to modify a few files to get your servlet up and running:

Source Code

Create your servlet source with, at the very least, a doGet() method:

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/plain"); PrintWriter out = res.getWriter (); out.println ("hello world"); } }

Compile it

More importantly put it where your servlet engine is expecting it. Given a servlet engine context of /my-space which has a docBase of /the/path/to/my-space then you'll want to put your code in /the/path/to/my-space/WEB-INF/classes with appropriate modifications for the class' package.

Try javac -d /the/path/to/my-space/WEB-INF/classes

Adjust Tomcat

If you've created your servlet engine context correctly you need to nothing more.

Fiddle with Init Parameters etc.

Create /the/path/to/my-space/WEB-INF/web.xml by copying the example in the Tomcat distribution! For example, to access your HelloWorldServlet as /my-space/HWS instead of the more cumbersome /my-space/com.lunanbay.HellowWorldServletyou might add the following:

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>hello-world</servlet-name> <servlet-class>com.lunanbay.HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello-world</servlet-name> <url-pattern>/HWS</url-pattern> </servlet-mapping> </web-app>

The format of web.xml means you have to put all instances of servlet before servlet-mappings etc.

Servlets

Some things to do with servlets.

File Uploading Raw and Parsed File Uploading

File Uploading

Two examples of servlets doing file uploads:

  1. The raw form data as returned to the server
  2. The parsed output using Jason Hunter's MultipartRequest code