我设法解决了这个问题。我将解释如何为年龄字段使用简单的自定义验证器,对于员工,年龄字段必须大于 18。接下来假设验证器已经在 validators.xml 中声明并映射到操作上,并且在 ValidationException 情况下的消息是“员工应该年满 18 岁。”。
使用Firebug,我发现表单中错误区域的id是FormError。可以在 jqgrid 中配置回调函数 errorTextFormat,以便从服务器获取响应并进行处理。在 jqgrid 配置中,可以这样写
errorTextFormat : errorFormat,
与
var errorFormat = function(response) {
var text = response.responseText;
$('#FormError').text(text); //sets the text in the error area to the validation //message from the server
return text;
};
现在的问题是服务器将隐式发送包含整个异常堆栈跟踪的响应。为了解决这个问题,我决定创建一个新的结果类型。
public class MyResult implements Result {
/**
*
*/
private static final long serialVersionUID = -6814596446076941639L;
private int errorCode = 500;
public void execute(ActionInvocation invocation) throws Exception {
ActionContext actionContext = invocation.getInvocationContext();
HttpServletResponse response = (HttpServletResponse) actionContext
.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
Exception exception = (Exception) actionContext
.getValueStack().findValue("exception");
response.setStatus(getErrorCode());
try {
PrintWriter out = response.getWriter();
out.print(exception.getMessage());
} catch (IOException e) {
throw e;
}
}
/**
* @return the errorCode
*/
public int getErrorCode() {
return errorCode;
}
/**
* @param errorCode the errorCode to set
*/
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
还必须在struts.xml中配置如下:
<package name="default" abstract="true" extends="struts-default">
...
<result-types>
<result-type name="validationError"
class="exercises.ex5.result.MyResult">
</result-type>
</result-types>
...
<action name="myaction">
...
<result name="validationException" type="validationError"></result>
<exception-mapping result="validationException"
exception="java.lang.Exception"></exception-mapping>
</action>
...
</package>
这些是我在添加/编辑窗口中获取验证错误消息所遵循的步骤,现在它可以工作了。