?
Solved

Struts: how to display success or failed message

Posted on 2006-06-08
16
Medium Priority
?
3,186 Views
Last Modified: 2008-01-09
hi experts,

i am new to Struts and trying to figure a good way to display messages after submit a form. I want the forward page to be the same form as the submit page, but display "error" or "success" message to the users after they submit the form. I have tried a couple of things and does not work. Please help. thanks.
0
Comment
Question by:dodowoman
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 10

Expert Comment

by:radarsh
ID: 16863826
Hi dodowoman,

What kind of message is that? There can be two things here.
First, you can forward to a global success or error page. In this case,
a new page will open and display a message, with a back button.

Second, you display the message on the current screen itself. It will be
a forward to the originating page itself with a suitable success/error message
populated.

________
radarsh
0
 

Author Comment

by:dodowoman
ID: 16864551
thanks, but I alreardy knew what you said. my questions is "how to" user the error object in Struts to display the message on the page. some codes sample will be hellpful.
0
 
LVL 10

Accepted Solution

by:
radarsh earned 200 total points
ID: 16864606
You can go for ActionMessage based approach. On error or success, you populate ActionMessages with something like this:

say, this code goes inside your execute method of action.

ActionMessages errors = new ActionMessages();
errors.add("problem", new ActionMessage("Something is wrong", false));
super.saveErrors(request, errors);
return // to the original page.

http://struts.apache.org/struts-action/apidocs/org/apache/struts/action/class-use/ActionMessages.html
http://www.javaworld.com/javaworld/jw-09-2004/jw-0913-struts-p2.html

The above links provide some help.

________
radarsh
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 5

Expert Comment

by:gksinghiet
ID: 16867715
I the execute method of your action class do the following:

    ActionErrors errors = new ActionErrors();
    ActionForward forward = new ActionForward();
    YourForm pForm = (YourForm) form;

    if (pForm.getAddress().length() < 5) {
        errors.add("invalid_address", new ActionError("invalid_address"));
    }
    if (!errors.empty()) {
        saveErrors(request, errors);
        forward = mapping.findForward("failure");
    } else {
        forward = mapping.findForward("success");
    }
    return (forward);
}
Now declare success and failure forwards to the same page and on that page use <html:errors/> tag for displaying error message.
0
 

Author Comment

by:dodowoman
ID: 16870465
thanks to both experts, I think I am confused about "where" should we do the validation.

For example, if we want to validate a user password entry, we could do it either using javascript, or use the action class as qksinghiet showed-- but this only validates the existance of the entry.
However, I also need to validate its correctness. then where should I do that? In action class? in form class? should I write another validation function in form class, then invoke it in the action class? I am sure you experts must have done someothing similar. some exmaple will be very helpful.

thanks very much.

0
 

Author Comment

by:dodowoman
ID: 16871857
I think I am getting close that I use "validate" in form class to validate the entry existance, and use "execute" in action class to validate from database end. I also used "ActionMessage" to replace "ActionError" which is deprecated.

But, however, the jsp still not showing anything after I put <html:errors/> tag even though the java class works fine...any suggestion?
0
 
LVL 5

Expert Comment

by:gksinghiet
ID: 16875756
If you are validating your form data, put the validation code in validate() method of your ActionForm else if you want to
do some business logic put it in execute() method of your Action.
As you can turn on and off the form validation by changing the form definition in struts-config.xml, you may found it handy when want to switch to client side validation.
For better performance use client side validation where ever possible.
0
 
LVL 5

Expert Comment

by:gksinghiet
ID: 16875796
>>But, however, the jsp still not showing anything after I put <html:errors/> tag even though the java class works fine...any suggestion?
Have you declared input attribute in your action declaration or have you declared global or local exception handlers.
For more detail refer:
http://javaboutique.internet.com/tutorials/excep_struts/
0
 

Author Comment

by:dodowoman
ID: 16888978
thanks,
but I feel the "Validator" tutorial just took me to another rout which is more complex than before.
My question is why error message did not show up after I coded in ActionForm and Action class, and in JSP file. I am not sure about your questions:
Have you declared input attribute in your action declaration or have you declared global or local exception handlers.?

But these are my codes:
public ActionForward execute(ActionMapping aMapping, ActionForm aForm, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException {
            
            LoginForm form = (LoginForm) aForm;
            String userName = form.getUserName();
            String password = form.getPassword();
            ActionErrors errors = new ActionErrors();
            
             ActionForward forward = new ActionForward();                  
            try{
                  
                  UserDAO db = UserDAO.getInstance();
                  RegistrationForm user = db.validateLogin(userName, password);
                  if (user!=null)
                  {      
                        aRequest.setAttribute("user", user);
                         forward = aMapping.findForward("success");
                  }
                  else
                  {      
                        errors.add("invalid entry", new ActionMessage("invalid_login"));
                        System.out.println("--ERRORS=== "+ errors.toString());                                    
                        saveMessages(aRequest, errors);
                    forward = aMapping.findForward("failure");
                  }
                  
                                  
                  }catch(Exception e)
                  {      
                        e.printStackTrace();
                        forward = aMapping.findForward("failure");
                        
                  }
      
                  return forward;


in ACTION FORM:
public ActionErrors validate(ActionMapping aMapping, HttpServletRequest aRequest) {  
                ActionErrors errors = new ActionErrors();  
             

                if ((userName==null) || (userName.length() <1) )  
                    errors.add("login id",new ActionMessage("error.login.required"));
                 
      if ((password==null) || (password.length()<1) )  
                    errors.add("password",new ActionMessage("error.password.required"));
            
            return errors;
        
             
                  } //validate  

}
}


IN JSP:

<html:errors />            
      
0
 
LVL 5

Expert Comment

by:gksinghiet
ID: 16892120
In case of validation in execute method you are explicitly forwarding the request to a page. But in case of validation in the validate() method the struts controller checks the ‘input’ attribute of the action for deciding who will be going to handle this error. So in that case you need to declare the input attribute. Also set validate to true as
<action-mappings>
     <action name="yourForm"
               path="/yourPath"
                 type="com.yourcompany.YourAction"
                 scope="request"
                 validate="true"
       input="/yourJsp.jsp"/>
</action-mappings>
0
 

Author Comment

by:dodowoman
ID: 16896884
I did exactly as you suggested, but the errors still does not show up.
0
 
LVL 5

Assisted Solution

by:gksinghiet
gksinghiet earned 200 total points
ID: 16900964
Any exception?
Have you configured validation plugin?
If not do the following steps:
1. In struts-config.xml add following lines:
        <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
                <set-property property="pathnames"
                  value="/WEB-INF/validator-rules.xml,/WEB-INF/validator.xml"/>
        </plug-in>
2.  Copy the validator-rules.xml to your application WEB-INF and cut and paste the error messages from it into a file called WEB-INF/classes/ApplicationResources.properties
3. Now create validation.xml in web-inf directory.
Still I am not sure that the steps 2 and 3 are required but you may give it a chance.
0
 

Author Comment

by:dodowoman
ID: 16955544
sorry for the late response, but I did every step you suggested, still no error shows up on the jsp page,
although I can see the error caught in Tomcat server console.

0
 
LVL 5

Assisted Solution

by:muktajindal
muktajindal earned 200 total points
ID: 17072303
Do you have "error.login.required" and "error.password.required" messages defined in your resource bundle??
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I came across an unsolved Outlook issue and here is my solution.
Often times it's very very easy to extend a volume on a Linux instance in AWS, but impossible to shrink it. I wanted to contribute to the experts-exchange community a way of providing a procedure that works on an AWS instance. It can also be used on…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question