The secure flag is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure flag is to prevent cookies from being observed by unauthorized parties due to the transmission of a the cookie in clear text.
To accomplish this goal, browsers which support the secure flag will only send cookies with the secure flag when the request is going to a HTTPS page. Said in another way, the browser will not send a cookie with the secure flag set over an unencrypted HTTP request.
By setting the secure flag, the browser will prevent the transmission of a cookie over an unencrypted channel.
Setting the Secure Flag
Following sections describes setting the Secure Flag in respective technologies.
Servlet 3.0 (Java EE 6)
Sun Java EE supports secure flag in Cookie interface since version 6 (Servlet class version 3), also for session cookies (JSESSIONID). Methods setSecure and isSecure can be used to set and check for secure value in cookies.
Servlet 3.0 (Java EE 6) introduced a standard way to configure secure attribute for the session cookie, this can be done by applying the following configuration in web.xml
<session-config> <cookie-config> <secure>true</secure> </cookie-config> </session-config>
In Tomcat 6 if the first request for session is using https then it automatically sets secure attribute on session cookie.
Setting it as a custom header
For older versions the workaround is to rewrite JSESSIONID value using and setting it as a custom header. The drawback is that servers can be configured to use a different session identifier than JSESSIONID.
String sessionid = request.getSession().getId(); response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure");
With this flag always set, sessions won't work in environments(development/test/etc.) that may use http. SessionCookieConfig  interface or setting custom header trick can be leveraged to configure setting of this flag differently for each environment and can be driven by application configuration.
<httpCookies requireSSL="true" />