Hallo, I have following issue:
I got a JSP in my /webapps/myapp/ folder, I want to pass it a value from a servlet.
I know you can use:
setAttribute(java.lang.String name, java.lang.Object value)
Do I have to create a session ?
but how do I insert it into the JSP and how does my servlet know which file to use ?
Thanks for your help
U don't need to create a session to send a value to the other JSP.
U can attach the information to the request object, with request.setAttribute(). U can retrieve this inforation using request.getAttribute(). The scope of this is at request level.
Otherway is to append the information to the JSP as a query string and get its value from the Querysting (ie request objecT).
The other two ways are creating a session and putting the values in the session object, or at application level using servlet context object.
Heinrich, Dasharatham has pretty well summarized the approaches you can take. I'll add these few notes.
As he said, you can use request.setAttribute(...), which probably makes the most sense. Just be sure that you invoke your JSP from the servlet by forwarding the request, not by redirect, e.g.,
The request 'ends' once the web page is delivered to your user and all the attributes you set using request.setAttribute(...) are lost. If you need for them to live beyond the request, then you'll need to store your object using session.setAttribute(...) instead. Also, if the 'thing' you're passing from your servlet to your JSP is an object other than a String, only the request.setAttribute(...) or session.setAttribute(...) method will work for you.
Appending to the query string, as suggested, is simple:
The former method is preferred as it doesn't require a round trip to the browser and back.