<%-- Instantiate the form validation bean and supply the error message map --%>
<%@ page import="com.mycompany.*" %>
<jsp:useBean id="form" class="com.mycompany.MyForm" scope="request">
    <jsp:setProperty name="form" property="errorMessages" value='<%= errorMap %>'/>

    // Ask the browser not to cache the page
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    // If process is true and a timestamp is present, attempt to validate and process the form
    String timestamp = request.getParameter("timestamp");
    if ("true".equals(request.getParameter("process")) && timestamp != null) {
        // Check timestamp
        if (!timestamp.equals(session.getAttribute("com.mycompany.MyForm.timestamp"))) {
        <jsp:setProperty name="form" property="*" />
        if (form.process()) {
            // Save a new timestamp in the session
            timestamp = ""+System.currentTimeMillis();
            session.setAttribute("com.mycompany.MyForm.timestamp", timestamp);

            // Go to success page
    } else {
        timestamp = ""+System.currentTimeMillis();
        session.setAttribute("com.mycompany.MyForm.timestamp", timestamp);

<head><title>A Simple Form That Prevents Duplicate Submissions</title></head>

<%-- When submitting the form, resubmit to this page --%>
<form action='<%= request.getRequestURI() %>' method="POST">
    <%-- email --%>
    <font color=red><%= form.getErrorMessage("email") %></font><br>
    Email: <input type="TEXT" name="email" value='<%= form.getEmail() %>'>

    <%-- zipcode --%>
    <font color=red><%= form.getErrorMessage("zipcode") %></font><br>
    Zipcode: <input type="TEXT" name="zipcode" value='<%= form.getZipcode() %>'>

    <input type="SUBMIT" value="OK">
    <input type="HIDDEN" name="process" value="true">

    <%-- Save the timestamp in the form --%>
    <input type="HIDDEN" name="timestamp" value="<%= timestamp %>">

    // Define error messages
    java.util.Map errorMap = new java.util.HashMap();
    public void jspInit() {
        errorMap.put(MyForm.ERR_EMAIL_ENTER, "Please enter an email address");
        errorMap.put(MyForm.ERR_EMAIL_INVALID, "The email address is not valid");
        errorMap.put(MyForm.ERR_ZIPCODE_ENTER, "Please enter a zipcode");
        errorMap.put(MyForm.ERR_ZIPCODE_INVALID, "The zipcode must be 5 digits");
        errorMap.put(MyForm.ERR_ZIPCODE_NUM_ONLY, "The zipcode must contain only digits");

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.