You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Edgaras <sk...@yahoo.com> on 2007/12/09 15:18:03 UTC

How to redirect error message

Hallo,

i want to redirect my errors "together" with page redirect...:  if user is logged he should see message "person created" on StartPage.jsp  and  if not   on Login.jsp. It works if I do directly forward,  but  if i redirect  Login.jsp  to  StartPage.jsp  error  massege is  gone. Could you help me :)

Thanks

Edgaras

struts-config.xml:



    <global-forwards>



        <forward 

            name="Start" 

            path="/pages/StartPage.jsp" />



    </global-forwards>



    <action 

            path="/CreatePerson" 

            type="actions.CreatePerson" 

            name="PersonForm" 

            input="/pages/JoinUs.jsp"

            scope="request"

            validate="false">

        

        <forward 

            name="success_create" 

            path="/pages/Login.jsp" />

Login.jsp:
....
<logic:present name="user" scope="session">
<logic:redirect forward="Start" />
</logic:present>
        <font color="red"><html:errors/></font>
....

CreatePerson.do:
...
ActionMessages errors = new ActionMessages();
errors.add"personcrated", new ActionMessage("message.person.created"));
saveErrors(request, errors);
return (mapping.findForward("success_create"));
.....










      __________________________________________________________
Sent from Yahoo! Mail - a smarter inbox http://uk.mail.yahoo.com

Re: How to redirect error message

Posted by Adam Hardy <ah...@cyberspaceroad.com>.
Gary Affonso on 09/12/07 23:58, wrote:
> Yayo wrote:
>> Errors are stored in a request scope attribute and after a redirect 
>> they're
>> lost because a new request is launched by the client browser. You must
>> explicitly (by code) store them in a session attribute to get them in the
>> second request.
> 
> Preserving the messages by hand will work, of course.  But there's a 
> nifty interceptor (MessageStoreInteceptor) that will do that for you now...
> 
> http://struts.apache.org/2.0.11/docs/message-store-interceptor.html

I keep meaning to put a stripped-down version of MessageStoreInterceptor up on 
the web - perhaps I should add it as a Jira issue?

Anyway, I wanted the interceptor to display success messages after a redirect.

The messages / errors only need to survive until the next request. So anything 
in the request I put into the session (in the after method) and in the before 
method, anything in the session, I remove and put into the request.

Very simple, fulfills the requirement and doesn't need any configuration telling 
it when to save or when to discard.


package org.permacode.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MessageHandlingInterceptor implements Interceptor
{
     private static final long serialVersionUID = 4491997514314242420L;

     private static final Log logger =
         LogFactory.getLog(MessageHandlingInterceptor.class);

     public static String FIELD_ERRORS =
         MessageHandlingInterceptor.class.getCanonicalName()
             + ".FieldErrors.key";

     public static String ACTION_ERRORS =
         MessageHandlingInterceptor.class.getCanonicalName()
             + ".ActionErrors.key";

     public static String ACTION_MESSAGES =
         MessageHandlingInterceptor.class.getCanonicalName()
             + ".ActionMessages.key";

     public void destroy()
     {
     }

     public void init()
     {
     }

     public String intercept(ActionInvocation invocation) throws Exception
     {
         logger.debug("entering interceptor....");
         before(invocation);
         String result = invocation.invoke();
         after(invocation, result);
         logger.debug("done interceptor.");
         return result;
     }

     /**
      * Handle the retrieving of field errors / action messages / field errors,
      * which is done before action invocation.
      *
      * @param invocation
      * @throws Exception
      */
     protected void before(ActionInvocation invocation) throws Exception
     {
         HttpSession session =
             ServletActionContext.getRequest().getSession();
         Object action = invocation.getAction();
         if (action instanceof ValidationAware)
         {
             // retrieve error / message from session
             ValidationAware validationAwareAction = (ValidationAware) action;
             Collection errors =
                 (Collection) session.getAttribute(ACTION_ERRORS);
             if (errors != null && errors.size() > 0)
             {
                 logger.debug("retrieve error from session "
                     + "to populate into action [" + action + "]");
                 Collection mergedErrors =
                     mergeCollection(validationAwareAction.getActionErrors(),
                         errors);
                 validationAwareAction.setActionErrors(mergedErrors);
             }
             Collection messages =
                 (Collection) session.getAttribute(ACTION_MESSAGES);
             if (messages != null && messages.size() > 0)
             {
                 logger.debug("retrieve message from session "
                     + "to populate into action [" + action + "]");
                 Collection mergedMessages =
                     mergeCollection(validationAwareAction.getActionMessages(),
                         messages);
                 validationAwareAction.setActionMessages(mergedMessages);
             }
             Map fieldErrors = (Map) session.getAttribute(FIELD_ERRORS);
             if (fieldErrors != null && fieldErrors.size() > 0)
             {
                 logger.debug("retrieve field errors from session "
                     + "to populate into action [" + action + "]");
                 Map mergedFieldErrors =
                     mergeMap(validationAwareAction.getFieldErrors(),
                         fieldErrors);
                 validationAwareAction.setFieldErrors(mergedFieldErrors);
             }
         }
         session.removeAttribute(ACTION_ERRORS);
         session.removeAttribute(ACTION_MESSAGES);
         session.removeAttribute(FIELD_ERRORS);
     }

     /**
      * Handle the storing of field errors / action messages / field errors,
      * which is done after action invocation when result is a redirect.
      *
      * @param invocation
      * @param result
      * @throws Exception
      */
     protected void after(ActionInvocation invocation, String result)
         throws Exception
     {
         Object action = invocation.getAction();
         if (action instanceof ValidationAware
             && invocation.getResult() instanceof ServletRedirectResult)
         {
             // store error / messages into session
             HttpSession session =
                 ServletActionContext.getRequest().getSession();
             logger.debug("store action [" + action
                 + "] error/messages into session ");
             ValidationAware validationAwareAction = (ValidationAware) action;
             session.setAttribute(ACTION_ERRORS, validationAwareAction
                 .getActionErrors());
             session.setAttribute(ACTION_MESSAGES, validationAwareAction
                 .getActionMessages());
             session.setAttribute(FIELD_ERRORS, validationAwareAction
                 .getFieldErrors());
         }
     }

     /**
      * Merge <code>col1</code> and <code>col2</code> and return the
      * composite <code>Collection</code>.
      *
      * @param col1
      * @param col2
      * @return Collection
      */
     protected Collection mergeCollection(Collection col1, Collection col2)
     {
         Collection _col1 = (col1 == null ? new ArrayList()
             : col1);
         Collection _col2 = (col2 == null ? new ArrayList()
             : col2);
         _col1.addAll(_col2);
         return _col1;
     }

     /**
      * Merge <code>map1</code> and <code>map2</code> and return the
      * composite <code>Map</code>
      *
      * @param map1
      * @param map2
      * @return Map
      */
     protected Map mergeMap(Map map1, Map map2)
     {
         Map _map1 = (map1 == null ? new LinkedHashMap()
             : map1);
         Map _map2 = (map2 == null ? new LinkedHashMap()
             : map2);
         _map1.putAll(_map2);
         return _map1;
     }
}

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: How to redirect error message

Posted by Gary Affonso <gl...@greywether.com>.
Yayo wrote:
> Errors are stored in a request scope attribute and after a redirect they're
> lost because a new request is launched by the client browser. You must
> explicitly (by code) store them in a session attribute to get them in the
> second request.

Preserving the messages by hand will work, of course.  But there's a 
nifty interceptor (MessageStoreInteceptor) that will do that for you now...

http://struts.apache.org/2.0.11/docs/message-store-interceptor.html

- Gary

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: How to redirect error message

Posted by Yayo <ed...@gmail.com>.
Errors are stored in a request scope attribute and after a redirect they're
lost because a new request is launched by the client browser. You must
explicitly (by code) store them in a session attribute to get them in the
second request.

^^

On Dec 9, 2007 3:18 PM, Edgaras <sk...@yahoo.com> wrote:

> Hallo,
>
> i want to redirect my errors "together" with page redirect...:  if user is
> logged he should see message "person created" on StartPage.jsp  and  if
> not   on Login.jsp. It works if I do directly forward,  but  if i redirect
>  Login.jsp  to  StartPage.jsp  error  massege is  gone. Could you help me
> :)
>
> Thanks
>
> Edgaras
>
> struts-config.xml:
>
>
>
>    <global-forwards>
>
>
>
>        <forward
>
>            name="Start"
>
>            path="/pages/StartPage.jsp" />
>
>
>
>    </global-forwards>
>
>
>
>    <action
>
>            path="/CreatePerson"
>
>            type="actions.CreatePerson"
>
>            name="PersonForm"
>
>            input="/pages/JoinUs.jsp"
>
>            scope="request"
>
>            validate="false">
>
>
>
>        <forward
>
>            name="success_create"
>
>            path="/pages/Login.jsp" />
>
> Login.jsp:
> ....
> <logic:present name="user" scope="session">
> <logic:redirect forward="Start" />
> </logic:present>
>        <font color="red"><html:errors/></font>
> ....
>
> CreatePerson.do:
> ...
> ActionMessages errors = new ActionMessages();
> errors.add"personcrated", new ActionMessage("message.person.created"));
> saveErrors(request, errors);
> return (mapping.findForward("success_create"));
> .....
>
>
>
>
>
>
>
>
>
>
>      __________________________________________________________
> Sent from Yahoo! Mail - a smarter inbox http://uk.mail.yahoo.com
>



-- 
"Sit tibi terra levis"

http://yayocaturas.blogspot.com/