Pritesh Pritesh - 3 months ago 19
Java Question

How to pass message from servlet to jsp?

I want to pass a status parameter from servlet to jsp. I am sending it through

response.sendRedirect("newpage.jsp?status=yes");


If
status = yes
then show success message in
<div>
and then set status to
null
. But when the
newpage.jsp
loads at the first time the value of status is
null
and it gives null pointer exception.

Same thing happens with session also.

<%
String status = request.getParameter("status");
System.out.println("Check Successful of Status"+status);
if (status.equalsIgnoreCase("yes")) {
System.out.println("Check Successful of Status");
%>

<div style="color: green;" align="center">Selected tenant approved successfully</div>

<script type="text/javascript"> window.location.href = window.location.href.split("?")[0]; </script>

<%
request.setAttribute("status1", null);
%>

Answer

In Servlet you can use

request.setAttribute("status","yes")

in jsp, you can retrieve using

request.getAttribute("status");

Yes, I missed the point

for above u need to use

RequestDispatcher rd = request.getRequestDispatcher("somefile.jsp");
rd.forward(request,response);

If u want to use response.sendRedirect("somefile.jsp"),

u can set the variable in session as

HttpSession session = request.getSession(false);

session.setAttribute("status","yes")

and get it back as

session.getAttribute("status").

Once used, u can remove it as

session.removeAttribute("status")