假设我使用Struts2验证框架(在我的示例中使用注释,但也使用xml,这是相同的)在操作中配置"每个方法"验证。假设我的操作中有三种公开的方法:
public class MyAction extends ActionSupport {
@Override
public String execute() throws Exception {
//some code here...
}
@Validations(
customValidators = {@CustomValidator(type="myCostomValidator", fieldName="myFieldName", shortCircuit=true, message="")}
)
public String info() {
//some code here...
}
@Validations(
customValidators = {@CustomValidator(type="myCostomValidator", fieldName="anotherFieldName", shortCircuit=true, message="")},
visitorFields = {@VisitorFieldValidator(context="update_context", fieldName="anObjectField", message="", shortCircuit=true)}
)
public String update() {
//some code here...
}
//getters, setters and other...
}
现在,这三个方法中的每一个都可以被调用,并具有不同的验证。如果验证失败,框架将设置必须配置到struts.xml:中的结果"输入"
<action name="myAction_*" method="{1}" class="com.test.gui.action.test.MyAction">
<result name="success">result1.jsp</result>
<result name="edit">result2.jsp</result>
<result name="input">result3.jsp</result>
</action>
如何为每种操作方法获得不同的"输入"结果?例如,如果info()方法的验证失败,我想访问一个页面,如果update()方法验证失败,则访问另一个页面。非常感谢。
我找到了这个解决方案:使用@InputConfig
注释。
使用此注释,您可以为验证错误设置"每个方法"的结果名称。因此,在struts.xml中,您可以为每个结果名称配置要访问的页面。
示例:
@InputConfig(resultName="input_update")
public String update() {
// perform action
return SUCCESS;
}
和struts.xml:<result name="input_update">jsp/input_update.jsp</result>
或:
@InputConfig(methodName="inputMethod")
public String update() {
// perform action
return SUCCESS;
}
public String inputMethod() {
// perform some data filling
return INPUT;
}
struts.xml:<result name="input">jsp/myInput.jsp</result>
请参阅struts.apache.org/docs/inputconfig-annotation.html 上的文档
它也可以通过为"工作流"拦截器设置参数来在struts.xml中设置输入结果名称,但它会影响操作中的所有方法:
<interceptor-ref name="workflow">
<param name="inputResultName">custom_input_result</param>
</interceptor-ref>
请参阅此处的文档struts.apache.org/docs/default-workflow-interceptor.html
您不必修改返回的结果名称。您的操作使用通配符映射,因此也可以将其用于JSP文件名。
<action name="myAction_*" method="{1}" class="com.test.gui.action.test.MyAction">
<result name="success">success.jsp</result>
<result name="input">result_{1}.jsp</result>
</action>