Details
Description
One of my frustrations with Struts is that errors and messages saved during the
request, either manually or automatically, are lost if my action returns a
forward with redirect="true".
I think this could be relatively easily fixed with the following mechanism:
When Struts handles a redirect forward, it checks if there are errors saved in
the request. If there are errors, It generates a unique ID, saves the errors in
the session using the unique ID as a session key, and appends the following
request parameter to the forward path: org.apache.struts.action.ERROR=<unique_id>
The same goes for messages saved in the request.
When Struts receives a request (after processPreprocess, for example), it checks
for the parameter org.apache.struts.action.ERROR and gets its value (the unique
id). Then it gets the errors saved in the session using the parameter value as a
key, saves the errors retrieved from the session in the request, and removed the
errors from the session.
This way, errors and messages are not lost anymore when redirecting (even with
chained redirects). It's totally transparent to the developer; it works even if
the user uses multiple browser windows and submits multiple concurrent requests;
and it shouldn't clutter the session (unless the browser doesn't redirect for
any reason)
Here's some code doing this:
protected String processErrorsAndMessagesBeforeRedirect(HttpServletRequest
request,
String uri) {
Object errors = request.getAttribute(Globals.ERROR_KEY);
if (errors != null)
Object messages = request.getAttribute(Globals.MESSAGE_KEY);
if (messages != null)
return uri;
}
protected void processErrorsAndMessagesAfterRedirect(HttpServletRequest
request) {
HttpSession session = request.getSession(true);
String errorParameterValue = request.getParameter(Globals.ERROR_KEY);
if (errorParameterValue != null) {
Object errors = session.getAttribute(errorParameterValue);
if (errors != null)
}
String messageParameterValue = request.getParameter(Globals.MESSAGE_KEY);
if (messageParameterValue != null) {
Object messages = session.getAttribute(messageParameterValue);
if (messages != null)
}
}
private String generateUniqueId(HttpServletRequest request, String type)
{ return type + "_" + TokenProcessor.getInstance().generateToken(request); } private String appendParameter(String uri,
String parameterName,
String parameterValue) {
StringBuffer buffer = new StringBuffer(uri);
if (uri.indexOf('?') >= 0)
else
{ buffer.append('?'); } buffer.append(parameterName);
buffer.append('=');
buffer.append(parameterValue);
return buffer.toString();
}
What's your opinion about this mechanism?
Attachments
Issue Links
- duplicates
-
STR-3032 Copy unaccessed messages/errors to session if redirecting
- Resolved