Search code examples
servletshttpsession

Need of getSession(boolean create) in HTTPServletRequest


Why doesn't container create the instance of HTTPSession when it receives first request, the way it does it for ServletContext or ServletConfig? Since sessions are managed by container, it would be logical to create session instance when it receives the first request, isn't it? Why don't we have simple getSession() method only i.e. why would someone need to invoke getSessin(false) in this fashion.


Solution

  • Creating a session has an impact on the response: it sets a cookie, and causes every properly encoded URL to have an additional jsessionid inside. You might not want that (for SEO reasons, etc.).

    It also has an impact on the server: a session object is created and kept in memory for every user visiting the application. You might not want that. Suppose for example that a bot sends a request every second to your application, and rejects the cookie set by the application server. Your webapp, after 30 minutes, would have 108000 useless sessions in memory.

    So starting a session is a deliberate choice by the programmer. If you need one, you create it. If you don't need it, you don't create it.