HelloWorld Example

HelloWorld Example

Posted in : Servlet Posted on : October 30, 2010 at 6:02 PM Comments : [ 0 ]

In this tutorial you will learn how to run your servlet program in tomcat 6

Hello World Example

The Hello World Example is the basic Http specific servlet example which shows the flow of the servlet. To white a basic servlet program you need to import javax.servlet.http.*; javax.servlet.*; and java.io.*;

javax.servlet is the generic servlet package It contains the ServletException class. The servlet exception is thrown by every servlet therefore it is necessary to include this package.

javax.servlet.http package contains the HttpServletRequest and HttpServletResponse interfaces and HttpServlet class. HttpServletRequest interface is used to get the servlet request by the service() method. HttpServletResponse interface is used to send the response of servlet to the client.  This class is an abstract class which extends the GenericServlet  If you are writing a servlet program the your servlet class must extend this HttpServlet class. This class contains doget(), doPost(), doTrace(), doDelete(), doPut() and getServletInfo() methods.

java.io is used by the servlet class because it contains the IOException class and PrintWriter class. IOException class is used by the to handle the exception related to the input output and PrintWriter class is used print the information.

An example of printing hello world program is given below

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
PrintWriter out = response.getWriter();
out.println("<body bgcolor=pink>");
out.println("<h1>Hello World Example</h1>");
Now add the following code into the web.xml file

Then start your tomcat. open your web browser type the following URL http://localhost:8080/hello The output will look like this

Download this example code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics