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:
  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

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

That HTML looks like this 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