Search code examples
javajqueryjspstruts-1

How can I save custom variables into the request in a Struts application in Java?


I'm using Struts 1.2 and J2EE 1.4. I'm pretty new to Struts and Java so hopefully there is a simple solution for my problem. I have a page set up like this:

<div class="success">
    HTML for success
</div>
<div class="error">
    <p>We are experiencing technical difficulties at this time. Please try your request again later.</p>
</div>
<div id="contact-form-block">
    <html:form action="/reg" id="contactform">

    <br /><html:text property="firstName"/><html:errors property="firstName"/>
        <p><input type="image" src="images/reset_btn.png" id="reset" name="reset" alt="Reset" /><input type="image" src="images/submit_btn.png" id="submit" name="submit" alt="Submit" /></p>
    </div>

</html:form>
</div>

Originally the success, error and contact us divs are all hidden. I have the contact form show up on click in a modal dialog box like this:

$('.success, .error, .success_header, .error_header').hide();
$('form#contactForm').show();

So, in my Action, I want to be able to send everything back to the same input forward regardless of whether there were validation errors or not. BUT I want to have a check on the jsp page in jQuery to check to see which dialog should be displayed:

  1. The Success dialog OR
  2. The contact-us dialog with the errors

Here is my action:

if ("reg".equalsIgnoreCase(contactUsForm.getAction())) {            

        ActionMessages errors = getErrors(request);

        errors = validate(contactUsForm);

        if (errors.isEmpty()) {

           //Save some variable to the request/response to say that registration was successful

        } else {
             //save something to say that registration was not successful
            saveErrors(request, errors);
        }
    }
    return actionForward;

Is there a way to set a variable in the Action that can be retrieved in the jsp page after the ActionForward is called. Preferably accessible by jQuery in the $(document).ready function?


Solution

  • You would use normal Struts and/or servlet spec mechanisms.

    You could just check to see if there are errors or not; they're stored in the request under the "org.apache.struts.action.ERROR" key; you don't need to add anything in particular, but if you really want to, you may.

    I prefer non-form data to be stored as a request attribute:

    request.setAttribute("haveErrors", true); // Or false, obviously.
    

    You then need to get the data out of the request in your JSP, and interpreted as JavaScript:

    $(function() {
        // Use normal JSP EL; haveErrors should display as a bare string, 
        // which is valid JS. Can modify as necessary if need be.
        var haveErrors = ${haveErrors};
    });