Java Servlets   «Prev  Next»

Lesson 3The simplest generated page
Objective How do you Write a Servlet that generates HTML?

Write Servlet that generates HTML

Generating HTML involves as little as four lines of code in your servlet’s doGet() method. Your method will:
  1. Set the content type of your response, to tell the browser you will be returning plain text HTML
  2. Get an output writer to which you can write HTML, attached to the response object
  3. Write HTML to that writer
  4. Close the writer
  5. The following MouseOver provides an example of this code:

import statements to permit short class names
  1. import statements to permit short class names
  2. define the servlet class
  3. define the doGet method and its two parameters
  4. list the exceptions this method might throw
  5. set the content of the response to "text/html"
  6. create an output writer attached to the response
  7. write HTML to the output writer. It will reach the browser eventually
  8. continue writing HTML to the output writer
  9. close the output writer
import statements to permit short class names

What does the code for the HelloWorld Servlet look like?

Java Servlet used to generate HTML (as was done back in 1999, 2000)
Java Servlet used to generate HTML (as was done back in 1999, 2000)

lines 1, 2 and 3 import statements to permit short class names
line 5 define the servlet class
lines 7, 8 define the doGet method and its two parameters
line 9 list the exceptions this method might throw
line 11 set the content of the response to “text/html”
line 13 create an output writer attached to the response
line 15 write HTML to the output writer. It will reach the browser eventually
lines 17-20 continue writing HTML to the output writer
line 21 close the output writer


This servlet will write out this HTML:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1> Hello, World!</h1>
This output was generated by the module 4 servlet.
</body>
</html>

That HTML looks like this in a browser:
What the Helloworld HTML should look like in a browser
What the Helloworld HTML should look like in a browser

Learn how to combine static and generated HTML in the next lesson.

First Servlet - Exercise

Click on the link below to experiment the Java Servlet concept.
First Servlet - Exercise

SEMrush Software