Servlet Example

0
707

In the last post we discussed about the Servlet basics and covered the different phases of its life cycle. Over here we would try to write a very simple ‘Hello World’ servlet class. This example would be an http servlet as they are the one widely and mostly used (not the Generic one).

Servlet Code Example

To make a simple java class a servlet, we need to first extend the HttpServlet class and then write any of the doGet() or doPost() methods. In the code example below we are just going to do the same and then add some lines to say hello to this world through a web servlet.

This needs to be executed on a web server like Tomcat or even any application server like WebLogic or Websphere can do. Here goes the simplest ever code:

Hello World Servlet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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 pw = response.getWriter();

      pw.println("<html>");
      pw.println("<head><title>Hello World Servlet</title></title>");
      pw.println("<body>");
      pw.println("<h1>My First Hello World Servlet</h1>");
      pw.println("</body></html>");
    }
}

The output from this program would be:

My First Hello World Servlet

Try it your own and let us know if you find it same or something different.
Happy Coding !!!

Previous articleServlet Overview and Life Cycle
Next articleMongoDB-Java Integration
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY