Sultan Ahmed
Sultan Ahmed

Reputation: 2220

how to send parameter from servlet to jsp page

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

Answers (3)

Yogesh Badke
Yogesh Badke

Reputation: 4587

You can not pass hidden params while using request.sendRedirect. You have following options to pass parameters to the JSP from servlet.

  1. Set request params in the url itself as

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.

  1. Use server-side forwarding as mentioned in the answer by Jaydip as shown below.

request.setAttribute("errorMessage", dbMessage); RequestDispatcher dispatcher = serveltContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response);

  1. Using session

    request.getSession().setAttribute("errorMessage", dbMessage);

    on the JSP, change code to

    String error_msg=(String)request.getSession().getAttribute("errorMessage");

  2. 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

Umesh Kumar Sharma
Umesh Kumar Sharma

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

Jaydip lakhatariya
Jaydip lakhatariya

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

Related Questions