"HelloWorld" Servlet with Eclipse and Tomcat Web server

In this tutorial, we will deploy a “HelloWorld” servlet using Eclipse. The Tomcat server is integrated in and launched by Eclipse.

Setting up Tomcat server on Eclipse

Create the "HelloWorld" servlet

  1. Create a new Dynamic Web Project by right click on the Project Explorer (or select menu File), New→Dynamic Web Project:


  2. Name it servletlabs. Select Target runtime as: Tomcat server v7.0. Finish.


  3. Right click on the servletlabs project, select New→Servlet:


  4. Name the Java package as: first.servlet and the Class name as: HelloWorld. Then click Finish.


  5. The file HelloWorld.java is open. Modify the doGet(…) function with following codes.

    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
     
    		response.setContentType("text/html");
    		PrintWriter pw = response.getWriter();
    		pw.println("");
    		pw.println("");
    		pw.println("");
    		pw.println("<h1>Hello World</h1>");
    		pw.println("");
    	}
  6. An error message appears to ask you about the missing library. Select to add the java.io.PrintWriter package to correct the error. Or you can manually add “import java.io.PrintWriter;” at the import section.
  7. Right click on the Tomcat server on the server tab, select Add and Remove…. Select to add the servletlabs project and click Finish.


  8. Start your Tomcat server.


  9. Open http://localhost:8080/servletlabs/HelloWorld on your web browser, you will get the message “Hello World”.


Exercises

  1. Verify whether we can create two servlets that have the same name but in different package ?
  2. Show another way to run a servlet from Eclipse apart from step 7→9.
  3. Create a servlet that shows the current time and date.
  4. Create a java function that generates a random number. Then, create a servlet that returns this number and says whether the number is odd or even.
  5. Update the servlet created in exercise 3 to says whether the generated number is a prime number.
teaching_assistant/servlet-jsp/helloworld-eclipse.txt · Last modified: 2013/07/17 15:15 by Walid Gaaloul
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0