Servlet Hello World

Last modified on July 27th, 2014 by Joe.

This tutorial is the standard Hello World program using Java Servlet. Using an IDE is the best choice to do development. It will help to increase the productivity. If you are in the early days of learning, like in college or school then you can use a simple text editor like Notepad++. My IDE of choice is Eclipse, but this tutorial is not tied with it. These are just my suggestions and you can go with any editors.

Web Application Structure

First lets start with a shell project structure and we should have directories created as shown below:

Web-Application-Structure

Note the webapps that’s where the application should be deployed in tomcat.

Hello World Servlet

package com.javapapers.servlet.introduction;

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 {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println("<html><body>");
		out.println("Hello World!");
		out.println("</body></html>");
		out.close();
	}
}

web.xml

In this web.xml we have defined Servlet mapping. Go through this linked tutorial to know about servlet mapping.

<web-app 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"
    version="2.4">
    <display-name>Servlet Hello World</display-name>    
    
    <servlet>
        <servlet-name>helloWorldServlet</servlet-name>
        <servlet-class>com.javapapers.servlet.introduction.HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>helloWorldServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
 
</web-app>  

This Servlet Hello World web application contains only the above two files. Download the complete project

Hello-World-Servlet-Output

Download:Servlet Hello World Project Source

Comments on "Servlet Hello World"

  1. Ranjeet Kharade says:

    Hey Joe once again nice and simple article…..

Comments are closed for "Servlet Hello World".