I have a client program on my laptop I am running that makes an HttpURLConnection to one of my servlets in my web application. This servlet creates an HttpSession and then uses HttpServletResponse.sendRedirect() to send the request on to a SessionScoped bean. That bean is throwing an exception saying that the HttpSession does not exist. If I access this servlet through a browser I don't run into this issue. So my question is:
Is there something specific with HttpURLConnection I have to set to get it to allow HttpSessions to be created?
If you have an independent application making HttpURLConnections to a J2EE webapp (JSF or otherwise), it's virtually certain that that application will establish a session that's completely independent of the session seen by that machine's web browser. And, in fact, if you have Firefox, IE, and Chrome all visiting the same app, each would have an independent session.
An IDE is no substitute for an Intelligent Developer.
Joined: Aug 30, 2011
Tim, I'm not trying to keep sessions between a browser and a stand-alone application. What I'm saying is the browser behaves as expected and the stand-alone app does not.
OK. The following is based on long-ago experience, so details may be incorrect, but it's more or less like this:
1. If your HttpURLConnection has cookies enabled (default, I think), then the sessionID should be automatically transferred back in a sessonid cookie, which the HttpURLConnection will automatically return on subsequent requests. Note that each HttpURLConnection object you create is distinct and would not share cookies/session IDs with any other HttpURLConnection objects. You should be able to extract the cookie from the HttpURLConnection as confirmation (or do a network trace). HttpURLConnection is a high-level interface that handles cookies automatically. If you were using a low-level network method instead, you'd have to write your own cookie management code.
2. If you are not using cookies, you MUST obtain the session ID from the server (usually it's the jsessionid appendage to returned URLs). And you MUST include that session ID in your URLs for subsequent requests.
The server cannot deduce the client's session ID. As I mentioned earlier, multiple clients would normally not share sessions, and in cases like NAT, multiple computers would appear to have the same source IP address. So the session ID has to be passed back and forth between client and server for as long as the session lasts, either in URLs or via cookies. On top of that, if you switch from HTTP to HTTPS, a new session ID is created and returned to the client and the old session ID becomes invalid.
Joined: Aug 30, 2011
Everything you said sounds right, Tim. And I was thinking the exact same thing. Here's the problem: I'm only making 1 call using 1 HttpURLConnection object. That's why I can't understand why a session isn't getting created.