无法在 PostConstruct 上设置 cookie

Can't set a cookie on PostConstruct

我使用此代码在页面加载期间设置 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 检查器或本地数据查看器中检查它时,它不会退出

有什么想法吗?

似乎是在呈现响应时首次引用该 bean。您不能在呈现响应阶段设置 cookie。 Cookie 在 HTTP 响应 headers 中设置。但目前 JSF 正忙于为响应 body 生成一些 HTML 输出,响应 headers 可能已经发送了很长时间。

您需要在 将第一位写入响应之前 设置 cookie body。

您可以使用 <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 以来,ExternalContext 上有新的 cookie 相关方法,例如 getRequestCookieMap(),这应该简化获取 cookie 的过程。 Faces utility class of JSF utility librarty OmniFaces 还有一些 cookie 相关的方法。

Faces.addResponseCookie("cookieName", cookieValue, "/", 60 * 60 * 24 * 365 * 10);
String cookieValue = Faces.getRequestCookie("cookieName");