"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
Create a new Dynamic Web Project by right click on the Project Explorer (or select menu File),
New→Dynamic Web Project:
Name it
servletlabs. Select Target runtime as:
Tomcat server v7.0.
Finish.
Right click on the
servletlabs project, select
New→Servlet:
Name the Java package as:
first.servlet and the Class name as:
HelloWorld. Then click
Finish.
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("");
}
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.
Right click on the Tomcat server on the server tab, select
Add and Remove…. Select to add the
servletlabs project and click
Finish.
Start your Tomcat server.
-
Exercises
Verify whether we can create two servlets that have the same name but in different package ?
Show another way to run a servlet from Eclipse apart from step 7→9.
Create a servlet that shows the current time and date.
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.
Update the servlet created in exercise 3 to says whether the generated number is a prime number.
Back to top