Java HttpSession

2019-03-11 05:22发布

Is HttpSession in java servlet is created only after

HttpSession s = request.getSession();

?

In my code I didn't write that, but when I use if (request.getSession(false) == null) ..., it doesn't work. Why?

5条回答
可以哭但决不认输i
2楼-- · 2019-03-11 05:25

A HttpSession is created when calling request.getSession().

But if you access a JSP by default it will automatically create a session.This behaviour can be disabled by using: <%@ page session="false">

Are you using JSP?

查看更多
做个烂人
3楼-- · 2019-03-11 05:27

Try to remove session cookies from browser and make another test. If it does not work then some other component is creating a new session before that call.

查看更多
Fickle 薄情
4楼-- · 2019-03-11 05:29

To make it complete:

  • session is not created, unless you call request.getSession(), in your servlet, use request.getSession(false) to get existing session without creating new session
  • if you use JSP page, session is automatically created for you - variable session - unless you specify <%@ page session="false" %>
  • even if your session is created automatically, you can use session.isNew() to find out, if it has been newly created
查看更多
够拽才男人
5楼-- · 2019-03-11 05:39

Read JavaDocs, it says clearly:

This says, request.getSession()

Returns the current session associated with this request, or if the request does not have a session, creates one.

And the other variant request.getSession(isCreate)

Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

If create is false and the request has no valid HttpSession, this method returns null.

To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.


Update

On a bit research, I have found that Session is not created unless request.getSession() is called somewhere. Since, The servlet container uses this interface to create a session between an HTTP client and an HTTP server. There are good chances that your Servlet container creates the Session for you by default.

refer:

  1. Java Doc HttpSession
  2. Discussion on JavaRaunch: is HttpSession created automatically?

But, to be safer side, use request.getSession() to get session, and use request.getSession(false) only when you need to verify if a session has already been created.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-03-11 05:43

In addition to Nishant's answer note that session can be created implicitly by JSP pages unless you configured them not to create a session with <%@ page session = "false" %>.

查看更多
登录 后发表回答