Search code examples
strutsstruts-1

How to access ActionErrors programmatically?


I know how to create ActionErrors, add some messages and display the messages in the JSP page. I think ActionError is like a list of error message. Here is the method to threat error that my system uses:

My Action

ActionErrors errors = new ActionErrors();
errors.add("customerId", new ActionError("error.customerId.required"));
this.saveErrors(request, errors);

my current JSP

<html:errors />

suppose i want to create ArrayList (in Java) of the error message in the JSP page. How to do this without change anything in in my Action.

my proposed JSP

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
    ArrayList<String> errMessage = new ArrayList<String>();
    //foreach (ActionErrors.message as message){
    //    errMessage.add(message);
    //}
%>
</body>
</html>

regards


Solution

  • Action

    If you save the errors in the request scope, e.g.:

    ActionErrors errors = new ActionErrors();
    errors.add("usr", new ActionMessage("User required", false));
    errors.add("pwd", new ActionMessage("errors.invalid", "Password"));
    saveErrors(request, errors);
    

    JSP

    You can get the errors in your JSP in order to populate your array list in the following way:

    <%@page import="java.util.ArrayList"%>
    <%@page import="java.util.Iterator"%>
    <%@page import="org.apache.struts.Globals"%>
    <%@page import="org.apache.struts.action.ActionErrors"%>
    <%@page import="org.apache.struts.action.ActionMessage"%>
    <%@page import="org.apache.struts.util.MessageResources"%>
    <%
    ArrayList<String> errMessage = new java.util.ArrayList<String>();
    ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
    Iterator<ActionMessage> iterator = errors.get();
    MessageResources resources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
    while (iterator.hasNext()) {
        ActionMessage error = iterator.next();
        if (error.isResource()) {
            errMessage.add(resources.getMessage(error.getKey(), error.getValues()));
        } else {
            errMessage.add(error.getKey());
        }
    }
    %>
    

    NOTE: This code example use Struts 1.3.10.