Understanding HttpServletRequest and cookies in JSF

痴心易碎 提交于 2019-12-23 04:53:07

问题


In order to create a "Remember me" login in JSF, I am trying to understand how Cookies work. I have created a brand new Web Application using JSF, with this bean that creates a Cookie expiring with the session:

CookieBean class

@ManagedBean
@ViewScoped
public class CookieBean implements Serializable {
    public void create() {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ec.addResponseCookie("MyTestCookie", "Hello Cookie", null);
    }    
}

and index.xhtml has this body:

<h:form>
    <h:commandButton value="Create Cookie!" action="#{cookieBean.create()}" >
        <f:ajax render="@form" />
    </h:commandButton>
    <p></p>
    <h:outputText value="Cookie value: #{cookie['MyTestCookie'].value}" /> 
</h:form>

As a result, when the page first loads, there is no cookie, correctly, because it's the first time the application runs, and no cookie is there.

After clicking the button once, no cookie is displayed. Why? The button invokes the cookieBean#create() method, and the ajax tag should force a revaluation of the outputText component. And this should generate an HttpSerlvetRequest with the cookie... or not? The cookie shows only after I press the button again!.

More surprisingly, when I press the refresh button of the browser, the cookie is not shown, although I'd expect to see it, because the older session is still alive.

It's like if (re)loading the page doesn't send an HttpServletRequest to the server...


回答1:


The #{cookie} refers to the cookies of the current HTTP request. If you add a new cookie, then it appears only on the HTTP response, but the HTTP request which is associated with this HTTP response does of course not have the cookie yet. It's only present in the subsequent request, depending on the age of the cookie.

You basically need to send a redirect afterwards to make the cookie available during rendering the HTTP response for the HTTP request.

As to the refresh matter, the request was most likely re-executed in the browser cache.



来源:https://stackoverflow.com/questions/11567277/understanding-httpservletrequest-and-cookies-in-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!