Reputation: 51661
I'm saving an image as a blob using the following, but I'm not sure how to carry a message through the final redirect to display to the user:
JSP file:
<%
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String action = blobstoreService.createUploadUrl("/servletimg");
%>
<form method="POST" action="<%= action %>" enctype="multipart/form-data">
...
</form>
The target servlet:
public class ServletImg extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
saveImg(...);
req.setAttribute("msg", "worked ok!");
resp.sendRedirect("/");
}
}
The final jsp page we get redirected back to:
if (request.getAttribute("msg") == null) {
Log.e("Hey we're missing the expected attribute!!!");
}
It all works ok, my image gets saved etc, but I don't see the "msg" attribute when redirected back to the main jsp page. Is there a way to carry a message through, or do I have to append it as parameters in the redirect, like:
resp.sendRedirect("/?msg=it worked ok!");
Thanks
Upvotes: 1
Views: 1123
Reputation: 1109362
A redirect basically instructs the client to fire a new HTTP request to the server. The initial request (and response) will be garbaged, including all of the attributes set. So yes, you really need to pass a parameter along the redirect URL.
response.sendRedirect("index.jsp?msg=" + URLEncoder.encode("worked ok!", "UTF-8"));
and then in JSP
<p>Message: ${param.msg}</p>
Alternatively, you can instead also just forward to the resource in question, i.e.
request.setAttribute("msg", "worked ok!");
request.getRequestDispatcher("/index.jsp").forward(request, response);
and then in JSP (as a shorthand for the ugly and discouraged scriptlet with request.getAttribute("msg")
):
<p>Message: ${msg}</p>
With a forward, the initial request will still be available in the targeted resource.
Upvotes: 1