How to Run a Java Servlet - dummies

By Doug Lowe

So exactly how do you run a Java servlet? First, you must compile the .java file to create a .class file; then you must move the .class file into a directory from which Tomcat can run the servlet. For testing purposes, you can move the servlet’s class file to c:tomcatwebappsExamplesWEB-INFclasses and then type an address like this one in your browser’s address bar:

http://localhost:8080/servlet/HelloWorld

You may also want to override the doPost method, which is called if the user requests your servlet from a form. In many cases, you’ll just call doGet from the doPost method, so that both get and post requests are processed in the same way.

The doGet method is called whenever the user enters the address of your servlet in the address bar or clicks a link that leads to your servlet. But many servlets are associated with HTML forms, which provide fields in which the user can enter data. The normal way to send form data from the browser to the server is with an HTTP POST request, not a GET request.

If you want a servlet to respond to POST requests, you can override the doPost method instead of, or in addition to, the doGet method. doPost has the same signature as doGet. In fact, it’s not uncommon to see servlets in which the doPost method simply calls doGet, so that both POST and GET requests are processed identically. To do that, code the doPost method like this:

public void doPost(HttpServletRequest request,
 HttpServletResponse response)
  throws IOException, ServletException
{
 doGet(request, response);
}