A Hello,World Servlet Servlet Tutorial Servlet Examples Run servlet on tomcat

Basic HelloWorld Program for Servlet

Servlet Definition – Servlet is a java code which runs at the servlet side and gives output in the form of html page.Its life cycle, init(),service() and destroy() is maintained by the container.

Here we will discuss how to run a simple servlet code. We will illustrate a simple HelloWorld.java for servlet .Lets us look at the code below so that we can correlate the concept.

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 {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


PrintWriter out = response.getWriter();



out.println(“<title>Servlet HelloWorld</title>”);



out.println(“<h1>Servlet HelloWorld at ” + request.getContextPath () + “</h1>”);




Here the methods doGet() and doPost() are the methods which get called by the service() method depending upon the fact that whether the request is post or get.How to call this servlet depends upon the entry in the web.xml file where the url-pattern tag indicates the url through which the servlet can be called.The imports above must be noted as the container will import the servlet APIs HttpServlet is the class from which our servlet class must inherit so as to process http requests.Let us look at he web.xml file now :

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app version=”2.4″ xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>










This is the web.xml file with HelloWorld.java as the only servlet.the servlet-class tag contains the fully qualified name of the java class file.Before that we need to compile the servlet code and put the class file into WEB-INF/classes folder of our tomcat server.The entry in the servlet-name tag represents the alias name for the servlet,meaning in the rest of the portion of web.xml file the servlet will be recoganized by this alias name.url-pattern tag denotes the url through which the servlet can be accessed from browser.Now to run the servlet type the following url in your browser :


Number of View :7899


  1. #1 written by asitkr October 28th, 2010 at 02:14

    Hello World Servlet Code

    RE Q

Content Protected Using Blog Protector By: PcDrome.