Assuming you are in a servlet 3.0+ environment and you don’t want to use web.xmlcookie-secure-flag to indicate the cookie, but programmatically set it:
ServletContextListener web.xml .
contextInitialized SessionCookieConfig:
public void contextInitialized(ServletContextEvent sce) {
boolean secure = ...
sce.getServletContext().getSessionCookieConfig().setSecure(secure);
}