4

I know we can do something like this:

<session-config>
 <cookie-config>
 <secure>true</secure>
 </cookie-config>
</session-config>

But what I want to achieve is to set this flag (true or false) based on some config.

Should we use a filter and how ?

Thanks

wero
  • 32,544
  • 3
  • 59
  • 84
kkung
  • 715
  • 4
  • 10
  • 18

1 Answers1

5

Assuming that you are in a servlet 3.0+ environment, and you don't want to use web.xml to specify the cookie-secure-flag but set it programmatically:

Implement a ServletContextListener and register it in the web.xml or via annotation.
In its contextInitialized method evaluate your secure flag from your config and set it on the SessionCookieConfig:

public void contextInitialized(ServletContextEvent sce) {
     boolean secure = ...
     sce.getServletContext().getSessionCookieConfig().setSecure(secure);
}
wero
  • 32,544
  • 3
  • 59
  • 84
  • Is there a way to retrieve within this method the http protocol used so that I can set the secure when it's HTTPS ? – kkung Feb 03 '16 at 21:40
  • @kkung this is a container specific config. Actually I don't know if this information is available during initialization of the context via the servlet api. – wero Feb 03 '16 at 22:11
  • @kkung did you ever find a solution to your question re: retrieving within the contextInitialized method the http protocol used? I need to do the same thing. – Binh Jul 30 '20 at 11:49