Reputation: 80769
I have a web app which contains two servlets, one to render my JSP pages, and another to generate PDFs. I use session state between the JSP pages and want to pass a session object to the PDF servlet.
Here's an example of how I set the session values in the JSP:
MyObject o = (MyObject)session.getAttribute("my.object");
if (o == null)
{
o = new MyObject();
session.setAttribute("my.object", o);
}
I then post off to my new servlet for the PDF generation from a link in my JSP
<a href="../pdfgen?f=d&t=c" target="_blank">Generate a draft report for review</a>
I thought I could use the HTTPRequest object to return the session in my servlet as follows:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession(false);
MyObject o = (MyObject) session.getAttribute("my.object");
}
Using the above code I get a null session object from the request.
If I use request.getSession(true)
I get a session object, but of course it doesn't contain anything in the attribute my.object
.
How is this supposed to work? What are the rules about sharing session state between servlets.
Tomcat 6
TIA
Upvotes: 0
Views: 3065
Reputation: 1453
Can you check if you have this by any chance declared :<%@ page session="false" %> ?
If you are using JSP implicit session object to set a value, it should be available to the servlet.
You code looks valid though..
Upvotes: 1
Reputation: 1108692
Don't set it in the JSP. It might be already too late then since JSP is part of the HTTP response and can already have committed the response. Whenever a new session needs to be created, the servlet container needs to add the session cookie to the HTTP response header. But that ain't going to happen when the response is already committed. Depending on the servletcontainer, you should have seen an IllegalStateException
in the server logs when attempting to do so.
Set it in the servlet instead, before forwarding the request to the JSP (the one of which you said that it "renders" JSP).
Unrelated to the concrete problem, don't use request.getSession(false)
in cases you need the session, just use request.getSession()
. Those potential NPEs and nullchecks are clumsy. Also writing raw Java code in JSP (using scriptlets) is considered poor practice.
Upvotes: 0