We should start understanding the servlets from the beginning. Lets start by making one program which will just print the “Hello World” on the browser. Each time the user visits this page it will display “Hello World” to the user.

As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server recieves the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.

Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object. HttpServletRequest object represents the client’s request and the HttpServletResponse represents the servlet’s response.

Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html. It is the standard MIME content type for the Html pages. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. To display the output on the browser we use the println() method of the PrintWriter class.

The code the program is given below:

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

public class HelloWorld extends HttpServlet{ 
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException,IOException{
  PrintWriter pw = response.getWriter();
  pw.println("<head><title>Hello World</title></title>");
  pw.println("<h1>Hello World</h1>");

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>

Alex Smirnov

Senior Java Developer. JAVA, PHP, Cold Fusion, SQL, Air, Flash.

More Posts