How to construct a custom error json response using the Struts framework

折月煮酒 提交于 2019-11-29 07:54:35

Struts2 actionErrors, fieldErrors provided by the ActionSupport. You can fill action errors or they are produced by the validation interceptor. For example

addFieldError("aggregation", “aggregationId not specified.”);
addFieldError("moreInfo", “https://www.iiitb-swn.com/docs/api/errors/40924”);

Then return json result as a response.

<result name="input" type="json">
  <param name="statusCode">409</param>
  <param name="errorCode">40924</param>
  <param name="ignoreHierarchy">false</param>
  <param name="includeProperties">^actionErrors.*,^fieldErrors.*</param>
</result> 

In this case I preferred to add the "fieldErrors" property as root object of the result, instead of filtering with regular expressions.

So, I added this to the action configuration (in this case with annotations)

@Result(name="input", type="json", params={"root","fieldErrors"})

And in the ajax configuration, under the success result, I used the returned JSON as

success : function(fieldErrors, textStatus, jqXHR) {
        for (var property in fieldErrors) {
            if (fieldErrors.hasOwnProperty(property)) {
                var this_field_err = fieldErrors[property];
                $('#submit_result').append(property+" error");
                for(var ix=0; ix<this_field_err.length; ix++) {
                    $('#submit_result').append(this_field_err[ix]);
                    $('#submit_result').append("<br>"); 
                }
            }
        }
    }

this adds to the #submit_result div I have the page

username error: Username must be at least 6 charachers long
password error: Password msut be at least 8 charachers long 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!