Site icon TestingDocs.com

How to create a Sample Servlet using Eclipse?

Introduction

Let us create a sample servlet and deploy it on the 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.

 

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

 

 

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

Create Servlet

 

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. Let us just say hello world and tell visitor to visit the 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.

 

Run the Servlet

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

http://localhost:8080/MyWebProject/HelloWorldExample

 

 

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

Exit mobile version