Search code examples
javavalidationstruts2visitor-patternmodel-driven

Struts2 model driven validation does not work


I have implemented model driven validation in my application but the validation does not work with following warning.

WARNING: The visited object is null, VisitorValidator will not be able to handle validation properly. Please make sure the visited object is not null for VisitorValidator to function properly

Any idea why?

Here is my Action class.

package actions;

import beans.CarListing;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ListCarAction extends ActionSupport implements ModelDriven{
    public String execute() {
        System.out.println("ListCarAction x" + carListing.getUrl());
        return SUCCESS;
    }

    private CarListing carListing = new CarListing();

    public Object getModel() {
        return carListing;
    }
}

Here is my ListCarAction-validation.xml

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
    "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
    <field name="model">
        <field-validator type="visitor">
            <param name="appendPrefix">false</param>
            <message>Car Listing: </message>
        </field-validator>
    </field>
</validators>

And here is the bean validator XML named CarListing-validation.xml.

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
    "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
    <field name="url">
        <field-validator type="requiredstring">
            <message>URL is required field.</message>
        </field-validator>
        <field-validator type="stringlength">
            <param name="minLength">1</param>
            <param name="minLength">30</param>
            <message>The URL must be at least 1-30 characters.</message>
        </field-validator>
    </field>
</validators>

Solution

    1. Ensure you are using a correctly configured Interceptor Stack for your Action, including all of the following interceptors in this order: modelDriven, params, validation. There are others interceptors among them, it's only important that they're not switching position with each other)

    2. Make sure that the CarListing-validation.xml file is put in the beans package, along the CarListing.class file, not in the actions package, where instead there is the other xml file.