Reputation: 155
I'm trying to do something that looks small but it's failing. I'm trying to send a response message back to a jsp when login fails but not being able. As of now I can only redirect back to the jsp but cannot display a message from the servlet on it. This is the servlet part of the redirection:
if (count > 0) {
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
I tried to print a message using PrintWriter and the redirect but failed because I couldn't get how to receive the message in the JSP. I also read that I shouldn't redirect but rather I should just forward from the servlet. How can I do this? Please help with the code patch to forward from servlet as well as that one to receive in JSP. Thanks
Upvotes: 13
Views: 73256
Reputation: 1109875
If you insist to use redirect instead of forward, then you have 2 options:
Pass the message as request parameter
String message = "hello";
res.sendRedirect("adminHome.jsp?message=" + URLEncoder.encode(message, "UTF-8"));
so that you can display it in JSP as follows
<p>Message: ${param.message}</p>
It's only visible in the browser address bar as well and you aren't able to pass non-standard Java objects this way.
Store it in session
String message = "hello";
req.getSession().setAttribute("message", message);
res.sendRedirect("adminHome.jsp");
so that you can display (and remove) it in JSP as follows:
<p>Message: ${message}</p>
<c:remove var="message" scope="session" />
Removing is important, otherwise it sticks there for the entire session.
However, if you're open to using forward instead of redirect, it's more elegant:
String message = "hello";
req.setAttribute("message", message);
req.getRequestDispatcher("/adminHome.jsp").forward(req, res);
and display it as follows in JSP
<p>Message: ${message}</p>
${}
things.Upvotes: 37
Reputation: 103155
You can save the message in the request and then forward to the jsp rather than redirect.
request.setAttribute("msg", "The actual error message to be displayed");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/yourpage.jsp");
rd.forward(request, response);
Then on the jsp page you have access to the message via the request.
Upvotes: 2
Reputation: 773
Set your message as an attribute of the request object:
request.setAttribute("message", messageString);
Use a RequestDispatcher to dispatch the request and response objects to the jsp:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("urlString");
dispatcher.forward(request, response);
Access it in your JSP using Expression Language syntax:
${message}
Upvotes: 3