views:

405

answers:

1

I have a servlet based application that creates a session and stores some information the first time it is accessed. This information is used in subsequent pages. The process runs into trouble if the initial url is clicked from inside a msword document. The servlet creates a session and sends the response back. The response is displayed in a newly opened browser. A link clicked from inside the browser creates a new session. Any subsequent urls clicked from the browser reuse the second session

Is there a way to force the server to recognize the initial session on the second request?

I created a sample servlet that retrieves a session and writes the ID along with a new link to call back to itself.

Below is the test servlet

public class SessionServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
     StringBuffer sb = new StringBuffer();
     sb.append("<HTML>\r\n<HEAD>\r\n<title>\r\nServlet Session Test\r\n</title>\r\n");
     sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
     sb.append("</HEAD>\r\n<BODY>\r\n");

     HttpSession userSession = request.getSession(true);

     if (userSession.isNew()) {
      sb.append("User Session is new\r\n");
     } else {
      sb.append("User Session is old\r\n");
     }
     sb.append("<br>User Session ID = " + userSession.getId() + "<BR>");

     sb.append("URL <a href=\"http://localhost:9080/myTestApp/SessionTest\"&gt; Session Test </a>");
     sb.append("</BODY> </HTML>\r\n");

     response.setContentType("text/html; charset=UTF-8");
     ServletOutputStream sos = response.getOutputStream();
     sos.write(sb.toString().getBytes("UTF-8"));
    }
}
A: 

Install a web debugger like Fiddler or do a Wireshark capture and I bet your JSESSIONID cookie is not being sent on the HTTP request. I have seen this with links from Microsoft Word that open in IE.

What I have done is change your code to request.getSession(false) and if you get null back, then do a response.sendRedirect back to yourself with an additional querystring parameter (e.g. newSession=true) appended to the URL. When the request comes back in with this additional parameter, then do a request.getSession(true). Hopefully, this will find yoru existing session, but if not it will create a new session. Be careful not to put you code in an infinite sendRedirect loop. This works because when IE makes the second HTTP request, it sends the cookies.

Kevin Hakanson