Lesson 9 | Processing a form in a servlet |
Objective | Write a servlet doPost() that processes a form. |
Processing Java Servlet
How do you post Data from form fields to Servlets?
Most servlets do a lot more with form fields than just echo them back to the user.
They use the information to look up accounts in a database, or to add orders to a list, or to send email to notify someone of a transaction.
In the modules that follow you will learn how to write servlets with this kind of server-side power.
Java Servlets
The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web
content technologies such as PHP, CGI and ASP.NET. Servlets can maintain state across many server transactions by using
- HTTP cookies,
- session variables or
- URL rewriting.
Because your doGet()
generated the FORM
tag, you know that it has METHOD=POST
.
Your doPost()
method will be called when the user submits the form. That method will need access to the form fields that the user entered before submitting the form. Those fields are available in the HTTP request object that is passed as the first parameter to
doPost()
. You call the getParameterValues()
method, which returns an array of String references, like this:
String[] vals = req.getParameterValues("name");
if (vals != null)
{
String name = vals[0];
if (name.length() > 0){
out.println("Hello " + name);
}
else{
out.println("Hello who ever you are");
}
}
getParameterValues
When you call getParameterValues
, be sure to pass the same string that you used for the NAME
attribute of the INPUT
tag in your generated HTML. You will also need to check that the reference you get back is not null
, and that the lengths of the individual strings you might use are not zero. Users do not always fill fields in, and it is possible for someone to write HTML that calls this same servlet with METHOD=POST
but does not send up these form fields to you.
Review what you have learned in this module.
Processing Forms - Exercise