Share on Google+Share on Google+

Java Servlet : Hello World Example

Advertisement
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{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Hello World</title></title>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
out.println("</body></html>");

}
}

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">
<display-name>ServletExample</display-name>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>net.roseindia.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern> /hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>

</welcome-file-list>
</web-app>

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

Output :

Advertisements

Advertisement

Posted on: October 4, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.