Thursday, 14 April 2016

How to add and display errors in Struts 2x ?


Adding Action Errors

Action : Add the errors as required inside action methods, before returning a result.
addActionError( getText("error.user.add") );

JSP
Add s:actionerror tag, where to show the added errors on JSP page.
<div class="errors"> <s:actionerror /> </div>


Adding Action Messages

Action : Add the messages as required inside action methods, before returning a result.
addActionMessage( getText("success.user.add") );


JSP
Add s:actionmessage tag, where to show the added messages.
<div class="messages"> <s:actionmessage /> </div>


Adding Field errors

It is a special feature; by using it you can show errors specific to a particular field.
Action : Add the field errors as required inside action methods, before returning a result.

boolean isOk = true;
if( msisdn==null || "".equals(msisdn) ) {
   addFieldError("msisdn", getText("validation.msisdn.required"));
   isOk = false;
}
if( email==null || "".equals(email) ) {
   addFieldError("email", getText("validation.email.required"));
   isOk = false;
}

if(! isOk)
  return INPUT;
// business logic here, in case of no error

JSP file
<s:textfield name="msisdn" size="20" />
<div class="errors">
   <s:fielderror>
      <s:param>msisdn</s:param>
   </s:fielderror>
</div>

<s:textfield name="email" size="20" value="" />
<div class="errors">
   <s:fielderror>
      <s:param>email</s:param>
   </s:fielderror>
</div>

No comments:

Post a Comment

Note: only a member of this blog may post a comment.