struts2 actionerrors, fielderrors return as json and display errors on the form - AJAX, Liferay Portal, Portlet

China☆狼群 提交于 2019-12-11 13:19:22

问题


I am wondering if anybody can throw any ideas on the following.

Got an Action class with validate() method returning input JSP with actionErrors, fieldErrors when validations fail.

I would like to get only the validation errors (JSON data ? ) and display the errors on the existing page and highlight the fields, rather than refreshing whole JSP with new response JSP.

JQuery is used on client side, Struts2 as MVC framework, Liferay as Portal server.

The following is the code that I tried,

public void validate() { 
    setActionErrors(validateData(this));
}
<result-types>
        <result-type name="json" class="org.apache.struts2.json.JSONResult"/>
</result-types>

<interceptors>
    <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
</interceptors>             


<action name="saveDataAsync" class="MyActionClass" method="addDataAsync">
    <result name="success">/jsp/addDataAsync.jsp</result>
    <result name="input" type="json">
    </result>
</action>
<portlet:actionURL name="saveData" var="saveDataActionURL">
   <portlet:param name="struts.portlet.action" value="/saveDataAsync"/>
</portlet:actionURL>
jQuery.ajax({
            type: 'POST',
            url: "<%=saveDataActionURL%>", 
            data: jQuery("#form").serialize(),
            dataType: 'json',
            success: function(data) {

                alert("data" + data);
            }
});

After execution of validate method. the flow is executing default method of action class, even when there are errors added to errorlist and set through setActionErrors() method. I could see resultcode : as "input" and result: as "jsonresult" when the interceptors and invoke methods get called.

I really appreciate any help on this problem.


回答1:


You can configure INPUT result to your action of type json and use includeProperties parameter to specify generated JSON.

<result name="input" type="json">
  <param name="ignoreHierarchy">false</param>
  <param name="includeProperties">^actionErrors\[\d+\],^fieldErrors\['\w+'\]\[\d+\]</param>
</result>

The action class should extend ActionSupport, so these properties will be available.



来源:https://stackoverflow.com/questions/24966334/struts2-actionerrors-fielderrors-return-as-json-and-display-errors-on-the-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!