Java Servlet example eclipse

Steps to create Sample Project Using Java Servlets

Lets see how to create a sample web application using Java Servlets and widely used Web server TOMCAT in Eclipse.

Environment :

  • Eclipse Java EE IDE for Web Developers. Version: Kepler Service Release 1
  •  Server info: Apache Tomcat/7.0.37
  • Servlet version: 3.0
  • JSP version: 2.1
  • Java version: 1.8.0_40

Create a new Project by navigating to File -> New -> Dynamic Web Project

Java Servlets

Java Servlets

Create a package (The use of the default package is discouraged.) under that create a new servlet by navigating File -> New -> Servlet

Servlet

New Servlet

One can observer in the screen shot, by default Our servlet’s Super class is javax.servlet.http.HttpServlet, we can change it to javax.servlet.GenericServlet which is used for developing protocol independent applications. Former is used for developing protocol dependent applications.

Servlet

Servlet

As we are extending HTTPServlet, it is an abstract class, need to override at least one method. The methods normally overridden are: init, destroy, doGet, doPost, getServletInfo. Same mentioned in the above screenshot.

Once Servlet is created need to do mapping in web.xml

ServletMapping

ServletMapping

Update the doGet method in the Servlet class

package com.aaj.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public TestServlet() {
    super();
  }

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    out.println("Welcome to All About Java <br> First Servlet Application ");
   }

  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
  }
}

Run the application. Right Click on the Project and click on Run on Server (If you already configured Server on your Eclipse).

Tomcat

Tomcat

Output of the program will be

Tomcat

Tomcat

2 thoughts on “Java Servlet example eclipse

Leave a Reply

Your email address will not be published. Required fields are marked *