J2EEOnlineJ2EE





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



HelloWorld Servlet Structure
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