Java Servlets   «Prev  Next»

Hello World - Servlet Exercise

The simplest generated page

Your first Real Servlet

Objective: Write a servlet that generates HTML.

Exercise scoring

This exercise is worth 5 points. The exercise is auto-scored, which means that all you have to do to receive credit for it is click the Submit button below.

Background/overview

In this lesson you saw how to code a servlet. Now try it yourself.

Download files

You can use your Simplest code from the previous module as a starting point. Copy it to another file, and change the class name from Simplest to HelloWorld. Do not forget to add an import statement for java.io.*. If you do not have this code any longer, you can download the code, Simplest.java , from the Exercise download.

Instructions

Write a servlet called HelloWorld that generates this HTML:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, World!</h1>
This output was generated by my own servlet.
</body>
</html>

After entering your Java code into a file called HelloWorld.java, follow these steps:
  1. Compile the servlet.
  2. Copy the .class file to the directory where JSDK server looks for servlets. Remember, in the previous module you set this path to
    // The path below is legacy path from year 1999
    c:\jsdk2.1\examples\WEB.INF\servlets.
    
  3. Start the JSDK server.
  4. Launch or switch to a browser.
  5. Enter this URL to check your code:
http://localhost:8080/servlet/HelloWorld
If you change your code and recompile while JSDK server is running, it may timeout and reset the connection between the server and browser. If this happens, when you reload the page in the browser, you will see your old output, not the result of your latest compile. Switch to the MS-DOS prompt where you started the server, stop it by pressing Ctrl+C, and start it again. Now you will see your new output.

Hints

Remember that you are overriding the servlet’s doGet() method. That method starts like this:
public void doGet (HttpServletRequest req, HttpServletResponse res) 
throws ServletException, IOException{

Your method should start by setting the response type and creating a writer from the response object that was passed to doGet(), like this:
res.setContentType("text/html"); 
PrintWriter out = res.getWriter(); 

To emit a line of HTML, print it to the writer you created from the response object that was passed to doGet(), like this:
out.println("<html><head><title>Hello, World!</title></head>");

Do not forget to close the writer after you have written all your HTML.