Monday, April 25, 2011

Struts 2 - A simple server-side validation example

There are many options for performing validation in Struts 2.  Below are steps I used to add server-side validation to a Struts v2.2.1.1 web project.
  1. Add validate() method to Action class.  Since my Action classes already extend ActionSupport, it's simple to override the default validate() implementation to provide my custom validations.
    public void validate() {
        logger.debug("Entering validate()");

        if ( tag.getName().length() == 0 ){
            addFieldError("name", getText(""));
    This example simply verifies the "name" attribute of the POJO named Tag exists, adding a FieldError when it doesn't.  Note the getText("") where we call the getText() method of ActionSupport to retrieve the value of the "" message key from the resource bundle.
  2. Add "input" result to struts.xml.  If our validation fails, the validate() method will automatically seek the "input" result.  Therefore, we'll add it to our action element in struts.xml.
    <action name="createtag"
        <result name="success">displayTag.jsp</result>
        <result name="input">tagForm.jsp</result>
  3. Add <s:actionerror /> and <s:head /> to JSP's. The <s:actionerror /> will render any errors as HTML.  The <s:head /> is optional but will include a CSS (xhtml by default) and a JavaScript utility file.
  4. Add error messages to resource bundle.  In my case, I added Tag name is required to my  Remember, we added a reference to in our validation code of the Action class.
  5. Add @SkipValidation to methods that don't require validation.  If your Action class is very simple with just a single execute() method then you can skip this step.  However, if you are using several methods in your action classes (ie. create(), edit(), list()) than you may want to add the @SkipValidation annotation to methods you don't need validated.  In my case, I had a list() and display() method that didn't require validation.

No comments:

Post a Comment