我已经将此代码设置为在页面加载期间设置cookie,但它无法正常工作:
标记:
<ui:fragment rendered="#{surveyWebBean.showQuestions}">
<ui:include src="/general/survey.xhtml" />
</ui:fragment>
代码:
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;
}
}
但是,当我尝试检索Cookie或在Google Chrome检查器或本地数据查看器中检查时,它不会退出
任何想法?
答案 0 :(得分:4)
似乎在呈现响应时首次引用bean。您无法在渲染响应阶段设置Cookie。 Cookie在HTTP响应标头中设置。但是目前JSF忙于为响应主体生成一些HTML输出,响应头很可能已经发送了很长时间。
您需要在第一位写入响应正文之前设置Cookie 。
您可以使用<f:event type="preRenderView">
在渲染响应实际开始之前调用bean侦听器方法。
<f:event type="preRenderView" listener="#{surveyWebBean.init}" />
public void init() { // (remove @PostConstruct!)
if (showQuestions) {
return; // Already initialized during a previous request in same session.
}
showQuestions = true;
UUID uuid = UUID.randomUUID();
CookieHelper ch = new CookieHelper();
ch.setCookie("COOKIE_UUID_SURVEY", uuid.toString(), 60 * 60 * 24 * 365 * 10);
}
无关具体问题,对于CookieHelper
,也许您在基于JSF 1.x的资源中找到它们,但您需要知道,因为JSF 2.0有新的cookie ExternalContext
上的相关方法,例如getRequestCookieMap()
,可以简化获取cookie的过程。 JSF实用程序库Faces
的OmniFaces实用程序类也有一些与cookie相关的方法。
Faces.addResponseCookie("cookieName", cookieValue, "/", 60 * 60 * 24 * 365 * 10);
String cookieValue = Faces.getRequestCookie("cookieName");