How to create a Sample Servlet using Eclipse?

Introduction

Let us create a sample servlet and deploy it on Tomcat server. First of all, create a Web Project in Eclipse. For instructions for creating a web project in eclipse, please go through the following question. ( http://www.testingdocs.com/questions/how-to-deploy-a-war-file-in-tomcat-using-eclipse/ )

 

Create Sample Servlet

Right-click the source folder and choose New >> Servlet as shown in below picture.

Create Sample Servlet

 

Give the package name and the Servlet class name of your choice.

 

Create Servlet Window

 

In the next wizard screen, enter servlet deployment descriptor specific information.

Create Servlet

 

Servlet Deployment Descriptor Information

In the next screen, choose the auto-generated method stubs. For simple servlets like ours doGet and doPost would suffice. Click on the Finish button to complete the process.

Give some implementation in the method stubs. I’m gonna just say hello world and tell visitor to visit my website for QA articles as shown :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("Visit www.TestingDocs.com for interesting QA stuff..!!"); out.println("</body>"); out.println("</html>"); } }

 

Save the changes and deploy the application in the Tomcat server as shown in the above link.

Note that trying to visit the URL before deploying the servlet, would display 404 not found error.

 

goGet method stub

Run the Servlet

Visit the servlet URL or run the servlet on the server :

http://localhost:8080/MyWebProject/HelloWorldExample

 

Servlet Running on Tomcat

 

You are done with creating, deploying, and running a sample Servlet in Tomcat server using Eclipse.