tags:

views:

40

answers:

3

How can I pass variable from servlet to jsp? setAttribute and getAttribute didn't work for me :-(

+1  A: 

You could set all the values into the response object before forwaring the request to the jsp. Or you can put your values into a session bean and access it in the jsp.

coding.mof
@coding.mof : Thanks dude. I did the same and it worked for me. :-)
Harsh
+4  A: 

Use request.setAttribute(..) and then getServletContext().getRequestDispatcher("/file.jsp").forward(). Then it will be accessible in the JSP.

As a sidenote - in your jsp avoid using java code. Use JSTL.

Bozho
Thanks Bozho! I dont know much about JSTL right now. But definitely I am going to learn it.
Harsh
+2  A: 

It will fail to work when:

  1. You are redirecting the response to a new request by response.sendRedirect("page.jsp"). The newly created request object will of course not contain the attributes anymore and they will not be accessible in the redirected JSP. You need to forward rather than redirect. E.g.

    request.setAttribute("name", "value");
    request.getRequestDispatcher("page.jsp").forward(request, response);
    
  2. You are accessing it the wrong way or using the wrong name. Assuming that you have set it using the name "name", then you should be able to access it in the forwarded JSP page as follows:

    ${name}
    
BalusC
Thanks a lot Guys :-)
Harsh