I went through this problem and I finally found a work around for the case where you want only one action to handle everything and keep the same URL on the browser:
http://localhost:8000/Struts2_Spring_Crud/student/add
The struts.xml would only be:
<action name="add" class="com.myapp.actions.StudentAction" method="insertOrUpdateStudent">
<result name="success" type="redirectAction">list</result>
<result name="input" type="tiles">/student.edit.tiles</result>
</action>
The first time your page loads, the class associated to "add" action is first called. Then the field student from the class is null. Then you can rely on that fact to clear the validation that strut did.
So you should add a validate() method to your action class that will delete the validation errors that strut stupidly found:
public class StudentAction extends ActionSupport{
MyStudent student;
public MyStudent getStudent(){
return student;
}
public void setStudent(MyStudent student){
this.student=student;
}
public String execute(){
if (student==null) return INPUT; //First time page loads. We show page associated to INPUT result.
return SUCCESS; // If student is not null and execute was called it means that everything went fine, we should return SUCCESS and go to the page associated to the SUCCESS result.
}
public String insertOrUpdateStudent(){
if (student==null) return INPUT;
return SUCCESS;
}
.....
@Override
public void validate(){ //
if (student==null){ //First time page loads, student is null.
setFieldErrors(null); //We clear all the validation errors that strut stupidly found since there was not form submission.
}
}
}
Struts first validates the form by the xml validator stuff and then calls your validate method.
When you hit submit on the form, then strut creates a MyStudent object, call the setStudent(...) and then it goes field by field of the form calling the getStudent() and then calling the set"FieldName" of MyStudent object. After that, it validates the student object by the xml validator stuff and then calls your validate Method.
If after calling the validate() method there are still errors, then strut will return with an "INPUT" result without calling the execute() or the insertOrUpdateStudent() method in your case.
Hope this helps!!!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…