None

Basic Servlet Reference

January 8, 2010

This post lists the basic code required to implement a Java servlet.

Handling GET requests

Create a method with the following signature:

public void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) 
                throws ServletException, IOException

Handling POST requests

Same as for GET, but with a different method name:

public void doPost(HttpServletRequest pRequest, HttpServletResponse pResponse) 
                throws ServletException, IOException

Getting page parameters

This works for both GET and POST parameters:

String lNewPassword = pRequest.getParameter("newPassword");

Writing The Response

An example of returning a string full of HTML back to the browser/caller:

PrintWriter lWriter = pResponse.getWriter();
lWriter.append(lHtml);
lWriter.close();
pResponse.setContentType("text/html");

Sending a 404 Response

Other error codes are available in SC_ contants.

pResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Token Invalid");

Sending A Redirect

Redirect to a different page client side

pResponse.sendRedirect("/path/to/go/to/");

Getting Path Requested

The path, hostname and port number are available through different methods on the HttpServletRequest instance

String lMachine = "http://" + pRequest.getLocalName() + ":" + pRequest.getLocalPort();
String lUri = pRequest.getRequestURI();