I've this code to set a cookie during page load, however it is not working:
MarkUp:
<ui:fragment rendered="#{surveyWebBean.showQuestions}">
<ui:include src="/general/survey.xhtml" />
</ui:fragment>
Code:
SurveyWebBean.java
@ManagedBean(name = "surveyWebBean")
@SessionScoped
public class EncuestasWebBean extends BaseBean {
private boolean showQuestions;
@PostConstruct
public void init() {
showQuestions = true;
UUID uuid = UUID.randomUUID();
CookieHelper ch = new CookieHelper();
ch.setCookie("COOKIE_UUID_SURVEY", uuid.toString(), 60 * 60 * 24 * 365 * 10);
}
//Getters and Setters
}
CookieHelper.java
public class CookieHelper {
public void setCookie(String name, String value, int expiry) {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
Cookie cookie = null;
Cookie[] userCookies = request.getCookies();
if (userCookies != null && userCookies.length > 0) {
for (int i = 0; i < userCookies.length; i++) {
if (userCookies[i].getName().equals(name)) {
cookie = userCookies[i];
break;
}
}
}
if (cookie != null) {
cookie.setValue(value);
} else {
cookie = new Cookie(name, value);
cookie.setPath("/");
}
cookie.setMaxAge(expiry);
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.addCookie(cookie);
}
public Cookie getCookie(String name) {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
Cookie cookie = null;
Cookie[] userCookies = request.getCookies();
if (userCookies != null && userCookies.length > 0) {
for (int i = 0; i < userCookies.length; i++) {
if (userCookies[i].getName().equals(name)) {
cookie = userCookies[i];
return cookie;
}
}
}
return null;
}
}
However, when I try to retrieve the cookie, or check it in the Google Chrome inspector or local data viewer, it doesn't exits
Any Idea?