I finally found a need for the “flash” scope that is so hyped with Ruby on Rails. Wondering how hard it would be to implement, I decided to just do it. I didn’t add it to WebWork, since we’re about to do a 2.2.2 release. Instead, I just added on to WebWork for my project. It couldn’t have been easier:
- Make a new result type flash that simply saves the action before redirecting
- Make a new interceptor that can be applied to all actions and adds any flashed actions it finds to the stack
Result:
public class Flash extends Redirect {
protected void doExecute(String finalLocation, ActionInvocation invocation) {
// before we redirect, let's save the state in to the session
Object action = invocation.getAction();
Map session = invocation.getInvocationContext().getSession();
session.put("__flash", action);
super.doExecute(finalLocation, invocation);
}
}
Interceptor:
public class FlashInterceptor implements Interceptor {
public String intercept(ActionInvocation ai) throws Exception {
Map session = ai.getInvocationContext().getSession();
Object action = session.get("__flash");
if (action != null) {
session.remove("__flash");
OgnlValueStack stack = ai.getStack();
stack.push(action);
}
return ai.invoke();
}
}
Now just make this both globally available to all your actions. Now instead of doing a chain or just not doing neat stuff like embedding multiple forms in a single page, just make your action’s INPUT result be of type flash and point back to the complex page that hosts the form. The original form values and new validation errors will just magically be there.
Note: that was done in less than 15 lines of functional code. It is also a great example of why you should learn the in’s and out’s of whatever libraries or frameworks you work with.
on May 30th, 2007 at 8:24 am
I am not entirely sure I like this solution. I would typically be more interested in adding individual “attributes” rather than entire action to flash scope when I use redirect-action.
If the action that i redirect to have properties with matching names, I want those initialized with that I added to flash scope, rather than having to extract them from previos action manually.