When using the different commit, the background through the validation rules file, check does not pass, when jumping to input view, the foreground display error message solution

Source: Internet
Author: User

1. The first type:

Recent projects using Struts2 (in fact, I think the background check, especially the struts of the check, can be placed in other places, such as to JS or business logic), and the system just also used the ExtJS, when the problem arises: if you submit data, Struts check does not pass, then struts will automatically return input, and ExtJS submit data is Ajax, regardless of the return value of struts, then the system will be error, the page can not display the information about the failure of the verification,

In this case, one way to do this is to add the input result set to the Struts.xml, redirect to another action handler, and then return the results of the AJAX request to the page, but the page does not display information about the validation failure. How can I resolve the details of the page display check failure?

Check the Internet, found struts2 new version of the Interceptor support to return the result set of the preprocessing listener function (for example: After the action method returns an input, I can intercept in the interceptor you return to the input view), we only need to implement this interface, You can then add a listener to the interceptor.

Look at the code:

[Java]View PlainCopyprint?
  1. Public class Exceptioninterceptor extends Abstractinterceptor {
  2. private static final Logger Logger = loggerfactory
  3. . GetLogger ("Exceptioninterceptor");
  4. @Override
  5. Public String Intercept (actioninvocation invocation) {
  6. try {
  7. //Increased monitoring
  8. Invocation.addpreresultlistener (new Mystrutslistener ());
  9. String retstring = Invocation.invoke ();
  10. return retstring;
  11. } catch (Exception e) {
  12. Logger.error (Stacktrace.getexceptiontrace (e));
  13. //to-do
  14. }
  15. }
  16. }
  17. //Implementation interface: Preresultlistener
  18. class Mystrutslistener implements Preresultlistener {
  19. @Override
  20. public void Beforeresult (actioninvocation actioninvocation, String result) {
  21. //Filter the request of result to input view
  22. if (Result! = null && result.equals ("input")) {
  23. //Set struts return value to null
  24. Actioninvocation.setresultcode (null);
  25. //Get fielderror error check information from Action
  26. Actioncontext Actioncontext = actioninvocation
  27. . Getinvocationcontext ();
  28. Valuestack VC = Actioncontext.getvaluestack ();
  29. map<string, object> ferrors = (map<string, object>) VC
  30. . Findvalue ("fielderrors");
  31. String returnmessage = null;
  32. for (map.entry<string, object> entry:ferrors.entrySet ()) {
  33. ArrayList list = (ArrayList) entry.getvalue ();
  34. if (list = null && list.size () > 0) {
  35. ReturnMessage = List.get (0). toString ();
  36. Break ;
  37. }
  38. }
  39. //Page write back JSON
  40. try {
  41. HttpServletResponse response = (httpservletresponse) actioncontext
  42. . GetContext (). Get (
  43. Org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
  44. Response.setcontenttype ("Application/json;  Charset=utf-8 ");
  45. Response.setheader ("Cache-control", "No-cache");
  46. PrintWriter writer = Response.getwriter ();
  47. Writer.print ("{success:false,message: '" + returnmessage + "'}");
  48. Writer.flush ();
  49. Writer.close ();
  50. } catch (IOException E1) {
  51. Logger.error (Stacktrace.getexceptiontrace (E1));
  52. }
  53. }
  54. }
  55. }


Finally, in the foreground parsing the received JSON data, feedback to the user, the effect and the struts failed to verify the message is the same. ^_^
Simple explanation: If you intercept input, remove a checksum from the struts stack and return to the page,

The above is the personal opinion, inevitably has the place which is ill-conceived

Loading source http://blog.csdn.net/jsjxieyang/article/details/8107547

---------------------------------------------------------------------------

The second type:

One: Define a result yourself

Java Code?
123456789101112131415161718192021222324252627282930313233343536 packageresult;importjava.io.PrintWriter;importjava.util.Map;importorg.apache.struts2.ServletActionContext;import net.sf.json.JSONObject;importcom.opensymphony.xwork2.ActionContext;importcom.opensymphony.xwork2.ActionInvocation;importcom.opensymphony.xwork2.Result;importcom.opensymphony.xwork2.util.ValueStack;publicclassvalidators_json implements Result {    @SuppressWarnings("unchecked")    @Override    publicvoidexecute(ActionInvocation arg0) throwsException {        //获值栈中fieldErrors的值        ValueStack vc = ActionContext.getContext().getValueStack();        Map<String, String[]>  ferrors = (Map<String,String[]>)  vc.findValue("fieldErrors");        //获得输出流        ServletActionContext.getResponse().setCharacterEncoding("utf8");        ServletActionContext.getResponse().setContentType("text/html");        PrintWriter out = ServletActionContext.getResponse().getWriter();        //将map转换为json        JSONObject json =JSONObject.fromObject(ferrors);        //想客户端输出        System.out.println(json.toString());        out.print(json.toString());        out.close();//        for (Map.Entry<String, String[]> entry : ferrors.entrySet())//           System.out.println("key:" + entry.getKey() + "  value:" + entry.getValue());    }}



Two, then modify the configuration file Struts.xml

Add a definition for type

xml/html Code?
123 <result-types>    <result-typename="validators_json" class="result.validators_json"default="true">   </result-type></result-types>


Use

xml/html Code?
1 <resultname="input"type="validators_json"></result


In this way, the message generated by the validation framework can be sent to the client in JSON mode, which can be defined by itself.
Implementation of AJAX+STRUTS2 validation framework asynchronous validation data.

When using the different commit, the background through the validation rules file, check does not pass, when jumping to input view, the foreground display error message solution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.