Reputation: 2220
I want to pass parameter from servlet to jsp page . That is why , in servlet , I have written the following code :
request.setAttribute("errorMessage", dbMessage);
response.sendRedirect(redirectURL + "index.jsp");
In index.jsp I have written the following code :
<%
String error_msg = (String)request.getAttribute("errorMessage");
out.println(error_msg);
if (error_msg != null) {%>
<div class="alert alert-danger">
<%=error_msg%>
</div>
<% } %>
But I do not have the value of errorMessage in index.jsp page. What is the reason ? Please help me . Point to be noted : error Message is not null .
Upvotes: 0
Views: 1024
Reputation: 4587
You can not pass hidden params while using request.sendRedirect. You have following options to pass parameters to the JSP from servlet.
response.sendRedirect(redirectURL + "index.jsp?errorMessage=", dbMessage);
and then in JSP change code to
String errorMsg = request.getParameter("errorMessage")
Error message will be visible in URL on the browser side.
request.setAttribute("errorMessage", dbMessage);
RequestDispatcher dispatcher = serveltContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
Using session
request.getSession().setAttribute("errorMessage", dbMessage);
on the JSP, change code to
String error_msg=(String)request.getSession().getAttribute("errorMessage");
Using cookie
Cookie errorCookie = new Cookie("errorMessage", dbMessage);
errorCookie.setPath(request.getContextPath());
response.addCookie(errorCookie);
On browser side you can read cookie via js or from the request itself
String error_msg = null;
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("errorMessage".equals(cookie.getName())) {
error_msg = cookie.getValue();
}
}
Upvotes: 3
Reputation: 306
You should write like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
**request.getSession().setAttribute("mango", "Mango is a sweet Fruit");**
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
Upvotes: 1
Reputation: 16
The problem here is you are using sendRedirect. Understand that sendRedirect will initiate new request to different url. Try to using forward or include to maintain the request parameter.
Upvotes: 0