Java Servlets   «Prev  Next»

Processing Java Sevlet Forms - Exercise

Using forms with Java Servlets


Objective:Write a servlet that generates and processes a form.

Exercise Scoring

This exercise is worth 10 points. To receive credit, paste your completed code in the text box provided below, and click the Submit button to send your code.

Background/overview

In the last three lessons, you saw the general structure of a form servlet, how to write a doGet() method so that it generates form HTML, and how to write a doPost() method so it processes the form. Now you are going to write a servlet like this yourself.

Instructions

  1. Write a servlet to generate and process a form. The doGet() method should generate this HTML:

<html><head><title>Using forms</title></head> 
<body><h1>Information from a form</h1> 
<form method=POST action="Url">
Enter your name: <input type=TEXT name=name><br>
<input type=submit value="Process Request">
</form></body></html>

Note that instead of “Url” your servlet should emit the actual URL of this servlet by calling req.getServletPath(). Note also that the name of the form field is “name”.
  1. The doPost() method should retrieve the “name” field, and use it to greet the user, like this:
    Hello, Kate
    Or, if the name has been left blank, the greeting should be:
    Hello, whoever you are
  2. Compile your servlet and test it with the JSDK mini-server.
Paste your code into the text area below once it's all working smoothly.