简体   繁体   中英

Java Servlet that Validates an HTML Form

I am new to Java and servlets and this is just a practice exercise I'm stuck on. I have a simple HTML form with two text fields for a first and last name, and two radio buttons for gender, plus a submit button. When the user fills out the form correctly the servlet returns a page that says "Welcome to my store Mr or Ms (depending on the gender button) and their first and last name. I have that all working correctly. What I can't get to work is a try-catch block that will alert the user if they've missed one of the name fields or didn't check a gender radio button. Is try-catch the way to go in this case or should I be using an if loop? I've inserted the try-catch in different spots but it doesn't seem to do anything. So my bottom line question is what is the best way of having the form validation work?

The HTML form:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"       "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Project 7</title>
</head>
<body  bgcolor="#FFFFD1">
<p align="left">
<h1>Please Enter Your Name</h1>
<form action="http://localhost:8080/Project/Main">
  First Name:&nbsp;<input type="text" name="firstName" ><br>
  Last Name:&nbsp;<input type="text" name="lastName" ><br><br><br>

  Gender &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   Male<input type="radio" name="rd" value = "0">&nbsp;&nbsp;
    Female<input type="radio" name="rd" value = "1"><br><br><br>

  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit Query">

</form>

</body>
</html>

The Servlet code:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Main")
public class Main extends javax.servlet.http.HttpServlet implements
    javax.servlet.Servlet {
static final long serialVersionUID = 1L;

public Main() {
    super();
}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Welcome to My Store";
    int radio = -1;

    String gender = "";

    radio = Integer.parseInt(request.getParameter("rd"));

    switch (radio) {
    case 0:
        gender = "Mr";
        break;
    case 1:
        gender = "Ms";
        break;
    default:
        gender = "";
        break;
    }

    out.println("<html>\n" + "<head><title>" + title + "</title></head>\n"
            + "<body bgcolor=\"#ffffd1\">\n" + "<h1 align=\"right\">"
            + title + "</h1>\n" + "<ul>\n" + "</ul>\n" + "" + "Thank you "
            + gender + " " + request.getParameter("firstName") + " "
            + request.getParameter("lastName") + "</body></html>");

}
}

I would POST the form data to the servlet. You would have to change the line

<form action="http://localhost:8080/Project/Main">

to

<form action="http://localhost:8080/Project/Main" method="post">

Then you would have to override the servlets doPost() method. Inside this method you can validate the parameters and if they are erroneous you simply resend the original HTML + some information about the erroneous fields. If the sent data was okay you can send the new HTML.

For example:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String title = "Welcome to My Store";

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");
    String gender = request.getParameter("rd");
    List<String> errors = new ArrayList<String>();

    response.setContentType("text/html");

    if (firstName.equals("") || null == firstName) {
        errors.add("First Name can't be empty.");
    }

    // Check the other fields the same way.

    if (!errors.isEmpty()) {
        // There are errors. Send the old HTML and for example add
        // a list with the error messages.
        String errorList = "<ul>";

        for (String error : errors) {
            errorList += "<li>" + error + "</li>";
        }

        errorList += "</ul>";

        // Insert errorList to the other HTML.
    } else {
        // No errors! Send the new HTML.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM