Tims Servlet Tutorial

Tutorial Home

  1. What are servlets ?
  2. The Hello World Servlet
  3. Running Servlets
  4. Reading Form Data
  5. Servlet Configuration
  6. Client Side Form Validation
  7. Cookies
  8. Sessions
  9. Authentication
  10. Dynamic Images
  11. Design, Testing, Security
  12. Servlets and Apache
  13. Using Servlets in SOCS

The Hello World Servlet


Shown below is a very basic 'Hello World' servlet.


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

public class HelloWorldServlet extends HttpServlet
{

 /**
 * Method to receive get requests from the web server
 * (Passes them onto the doPost method)
 * @param req The HttpServletRequest which contains the information submitted via get
 * @param res A response containing the required response data for this request
 **/

 public void doGet(HttpServletRequest req, HttpServletResponse res)
   throws ServletException, IOException
 {
  doPost(req,res);  			//  Pass all GET request to the the doPost method
 }

 /**
 * Method to relieve and process Post requests from the web server
 * @param req The HttpServletRequest which contains the information submitted via post
 * @param res A response containing the required response data for this request
 **/

 public void doPost(HttpServletRequest req, HttpServletResponse res)
   throws ServletException, IOException
 {
  res.setContentType("text/html");	//  Set the content type of the response
  PrintWriter out=res.getWriter();	//  PrintWriter to write text to the response
  out.println("Hello World");		//  Write Hello World
  out.close();			//  Close the PrintWriter
 }
}


This servlet will produce a simple text response every time it is called by the webserver.


You can see the output from this servlet by clicking here.

If you want to try this servlet out on your own system, just cut and paste it to a file called HelloWorldServlet.java and compile.

Very simply, this servlet extends from a base HttpServlet and overrides the two methods in HttpServlet which receive information submitted by the GET and POST methods (which shall be explained on the next page). When these methods are called, two objects are passed in, The HttpServletRequest, which contains all of the information submitted by the user for processing and the HttpServletResponse, which is used by the servlet for sending a response to the webbrowser. In this case the HttpServletRequest is ignored. The HttpServletResponse is simply used to send a quick message back to the webbrowser.


<< Previous Page | Next Page >>




Tims Home Page       |       Page last modified : 19 May 2003