Home Tutorial Servlet Java Servlet : Hello World Example


Share on Google+Share on Google+
Java Servlet : Hello World Example
Posted on: October 4, 2012 at 12:00 AM
In this tutorial, we are discussing about Servlet with simple Hello World Example.

Java Servlet : Hello World Example

In this tutorial, we are discussing about Servlet with simple Hello World Example.

Java Servlet : A servlet is web component managed by the container like Apache Tomcat that generates dynamic content. It receives requests from the web clients and responds back to the client across HTTP.

Servlet is configured in configuration file that is web.xml. Directory structure of your servlet is like -

Following are the steps  for writing simple hello world example of servlet.

Step1 : Write servlet, a POJO containing doGet() method which provide you the output of your program. 

 HelloWorld.java -

package net.roseindia;
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 out = response.getWriter();
out.println("<head><title>Hello World</title></title>");
out.println("<h1>Hello World</h1>");


Step 2 . Next map your servlet into configuration file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<url-pattern> /hello</url-pattern>


Step 3 . Now run your servlet on server and write url-pattern of servlet 'hello' on to the url.

Output :


Related Tags for Java Servlet : Hello World Example:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 4, 2012

Recommend the tutorial

Advertisements Advertisements