问题
Can you tell me how can I get the action exceptions , convert and send them as json errors. I am using the strust2 jquery plugin to validate my forms with ajax. The framework will do it automatically by defining the sj:submit validate=true
and annotating the actions
<s:form action="login">
<s:textfield name="username" />
<s:textfield name="password" />
<sj:submit button="true" validate="true" />
</s:form>
The action is:
@Validations(requiredStrings =
{ @RequiredStringValidator(fieldName = "username", key = "validate.required"),
@RequiredStringValidator(fieldName = "password", key = "validate.required")}
public String confirm(){
service.canLogin(username,password)
}
The canLogin
may throws exception, eg. when it can not connect to database or shomething.
To serialze the excption I added below:
<global-results>
<result name="error.core" type="json">
<param name="ignoreHierarchy">false</param>
<param name="includeProperties">
actionErrors\[\d+\], fieldErrors\..+$,actionMessages\[\d+\]</param>
</result>
</global-results>
When I submit the form with invalid data, the form validates correctly. When an exception rasies the page is not serializing json results.
During debug I found that two json calls are made to server, one with:
- All form data's
- struts.enableJSONValidation
- struts.validateOnly
and one only with all for data's
回答1:
I finally find the answer! Hope be useful for others...
The goal is catch bussiness exception and show them to user as ajax validation exceptions.
Set the target of the sj:form
to some dummy div analyze, your data and do what you want.
The jsp will be
<sj:submit button="true" targets="dummy"
validateFunction="formValidator" onBeforeTopics="removeErrors"
onSuccessTopics="formServerErrorAnalyze" validate="true"
key="form.btn.transfer" />
The js will be
$.subscribe("formServerErrorAnalyze", function(event, data) {
var data = event.originalEvent.data;
if (data=='Some Exception from server')
{
//Do some thing to show error.
//eg: $("#formerrors").html(data)
}
else {
// Put the content of dummy node into content and remove dummy html
var working = $("#dummy").contents();
var ref = $("#content").contents();
$("#dummy").append(ref);
$("#content").append(working);
}
$("#dummy").html('');
});
There is a bug in struts-jquery. If you do not set the target of sj:submit
the tag onSuccessTopics
will not fire! If this is solved, you do not need the dummy div any more.
来源:https://stackoverflow.com/questions/19934907/strust-2-jquery-plugin-show-action-exceptions-as-ajax-error