I am running a basic Struts2 application in which I got one confusion. My action class implements Preparable and ModelDriven interfaces and extends ActionSupport class.The model bean has a single property named "User".
My home page(jsp) has one input field corresponding to the only property "User" of a model bean.
In prepare() method I am initializing the bean and setting its property to some default value say "Test" and the model() method is returning this bean object.
In validate(), I have a validation that if "User" property of bean has value equals to "Test" then addFieldError else proceed.
public Student getModel() {
System.out.println("inside getModel.."+ st.getName());
return st;
}
public void validate(){
System.out.println("inside validate"+st.getName());
if(st.getName().equals("Test")){
addFieldError("name","blank field");
}
}
public void prepare() throws Exception {
st = new Student();
st.setName("Test");
}
Now, my question is When I am accessing the action directly then the the error comes and in console I got below logs:
inside getModel..Test
inside getModel..Test
inside validate...Test
but If I input any value say "Stack" in the form field and submit the form then validate method prints the value that user has input while model method is printing what prepare has initialized.
inside getModel..Test
inside getModel..Test
inside validate...Stack
Why so? Why both methods are not in sync? Do the validate method and model method are picking the property value from different locations?
Thanks.
The values are get/set by the order of the interceptor invocations. As long as the action is on the valuestack, after prepare
the params
interceptor is called getModel()
to get the object whose property should be set.
The modelDriven
interceptor also retrieves model from the valuestack. Any subsequent searches for the model properties via expression results to call getModel()
while the property isn't set yet. The params
interceptor sets property finally, then validation
interceptor is invoked, which is also retrieves getModel()
to get the property values that should be already set.
The console will look like above. It's a normal behavior of the interceptors until the action is executed. In the first case you didn't send values with the request, therefore the console prints what has been after prepare
. In the second the value is sent and property has been changed, so the console reflected it. Values are coming with the http request, so it's the same "location" in the scope of request.
来源:https://stackoverflow.com/questions/18044173/difference-in-the-property-value-fetched-in-validate-and-model-method-in-struts2