How to create a Sample Servlet using Eclipse?
Let us create a sample servlet and deploy it on Tomcat server. First of all, create a Web Project in Eclipse. For instructions 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.
In the next screen, choose the auto generated method stubs. For simple servlet 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 stuff as shown below:
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 Tomcat server as shown in above link.
Note that trying to visit the url before deploying the servlet, would display 404 not found error.
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.