Skip to content

Instantly share code, notes, and snippets.

@zgulde
Last active April 10, 2018 16:24
Show Gist options
  • Save zgulde/5264821761f82313e86109849d889a57 to your computer and use it in GitHub Desktop.
Save zgulde/5264821761f82313e86109849d889a57 to your computer and use it in GitHub Desktop.
a strategy for user input validation in a servlet/jsp application

In the servlet

usersDao = DaoFactory.getUsersDao();
// Create a user based on the submitted information
User newUser = new User(
    request.getParameter("username"),
    request.getParameter("email"),
    request.getParameter("password")
);

// Create a list to hold any validation error messages we encounter
List<String> errors = new ArrayList<>();

// Next we'll have a handful of if statements to check all of our validation constraints

if (usersDao.exists(newUser)) {
    errors.add("That username is already taken.");
}

boolean passwordsMatch = request.getParameter("password").equals(request.getParameter("confirm_password"));
if (! passwordsMatch) {
    errors.add("Password and confirm password must match");
}

if (newUser.getUsername().length() == 0) {
    errors.add("You must enter a password");
}

if (newUser.getEmail().length() == 0 || newUser.getEmail().indexOf("@") == -1) {
    errors.add("Please enter a valid email address");
}

if (newUser.getPassword().length() == 0) {
    errors.add("You must choose a password");
}

// once we're done with all the validation checking...

if (errors.isEmpty()) {
    // no errors
    usersDao.insert(newUser());
    response.sendRedirect("/login");
} else {
    // we have at least one validation error, go back to the register form
    request.getSession().setAttribute("errors", errors);
    response.sendRedirect("/register");
}

in the JSP

loop through any errors if they exist, and display each one

<c:if test="${! sessionScope.errors.isEmpty()}">
    <c:forEach var="error" items="${sessionScope.errors}">
        <p class="alert alert-danger">${error}</p>
    </c:forEach>

    <c:remove var="errors" scope="session" />
</c:if>

Notice that we remove the errors afterwords, that way if the user fills the form out again, we don't still have errors in our session

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment