Friday, July 25, 2008

Pass an encoded message resource in a redirect URL

Often you need to display a message/error on a JSP page but you want to redirect to the page so that it can be refreshed without reposting the form.  If you simply set redirect="true" in your struts-config.xml action forward you end up losing the request-scoped message when struts issues the redirect.

So what you need to do is 1) construct the message from a resource file, 2) encode the message, 3) issue a redirect and 4) display the message in the target JSP.

Access the bundle

org.apache.struts.util.MessageResources mr = getResources(request);
String message = mr.getMessage("the.message.key", optionalInterpolationArgument);

URL encode the message and issue a redirect

message = "message=" +, "UTF-8");
response.sendRedirect(request.getContextPath() + "/" + message);

Display the message

Note the use of <c:out /> here. If you just write out the message without doing any HTML escaping on it you open yourself up to an HTML-injection attack.
<c:if test="${!empty param.message}">
  <c:out value="${param.message}" />

Lookup message resources in a JSP file

Sometimes it may be better to just pass the message key itself and have the target JSP lookup the message and display it. The following snippet shows you how to lookup a message key:
<bean:message key="simple.message.key"/>
<bean:message key="interpolated.message.key" arg0="argument.value"/>

No comments: