Action errors are not shown on the JSP

2019-07-03 13:33发布

问题:

I have tried adding action errors in the Action class and printing them on the JSP page.

When an exception occurred, it is going into the catch block and it is printing "Error in inserting the Exception, Contact the Admin", in console.

In the catch block, I've added it with addActionError(), and I've tried printing it in jsp page...
but the message is not shown in jsp page.

What I may be missing or doing wrong ?

Struts mapping:

<action name="dataUpdate" class="foo.bar.myAction" method="updation">
    <result name="success" type="redirectAction">
        ../Aggregator/redirectToDataUpdate
    </result>
</action>

Action class:

public String updation() throws JiffieTransactionException{
    try {
        // do stuff...
    } catch (NumberFormatException e) {
        addActionError("Error in inserting the Exception, Contact the Admin");
        System.out.println("Error in inserting the Exception, Contact the Admin");
        e.printStackTrace();
    }
    return SUCCESS;
}

JSP code for printing action errors:

<s:if test="hasActionErrors()">
    <br></br>
    <div class="errors">
        <font color="red">
            <s:actionerror/>
        </font>
    </div>
</s:if>

回答1:

When you perform a redirectAction, a new Request is created, and hence all the actionMessages, actionErrors, along with all the other parameters (not expressly declared to be passed in the struts config) are lost.

Then

  • Use a default dispatcher result instead of a redirectAction result, or
  • use the MessageStore Interceptor to preserve errors and messages across the redirects, or
  • return a different result of type dispatcher in case of errors, eg. ERROR:

    <action name="dataUpdate" class="foo.bar.myAction" method="updation">
        <result name="success" type="redirectAction">....redirectToDataUpdate</result>
        <result name="error">previousPage.jsp</result>
    </action>
    
    public String updation() {
        try {
            // do stuff...
            return SUCCESS;
        } catch (NumberFormatException e) {
            addActionError("Errors... ");
            e.printStackTrace();
            return ERROR;
        }
    }
    


回答2:

Add an action message in catch block like :

addActionMessage("Error in inserting the Exception, Contact the Admin"); //in catch block

and then on jsp write:

<s:if test="hasActionErrors()">
  <br></br>
     <div class="errors">
       <font color="red">
              <s:actionerror/>
            </font>
     </div>
   <s:if test="hasActionMessages()">
     <div class="errors">
       <font color="red">
          <s:actionmessage/>
       </font>
      </div>
   </s:if>
  </s:if>