了解JSF中的HttpServletRequest和cookie [英] Understanding HttpServletRequest and cookies in JSF

查看:305
本文介绍了了解JSF中的HttpServletRequest和cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在JSF中创建一个记住我的登录信息,我想了解Cookie的工作原理。我使用JSF创建了一个全新的Web应用程序,使用此Bean创建了一个Cookie到期的会话:

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 >

CookieBean class

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

index.xhtml 有此身体:

<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>

因此,当页面首次加载时,没有正确的cookie,因为它是第一个

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.

点击按钮一次后,不显示任何Cookie。为什么?该按钮调用 cookieBean#create()方法,ajax标签应该强制重新赋值 outputText 组件。这应该生成一个 HttpSerlvetRequest 与cookie ...或不是?只有在我再次按下按钮后,cookie才会显示。

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!.

更令人惊讶的是,当我按浏览器的刷新按钮时, d期望看到它,因为较旧的会话仍然活着。

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.

就像if(re)加载页面不发送HttpServletRequest到服务器...

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

推荐答案

#{cookie} strong>当前HTTP请求。如果您添加了新的Cookie,则它只会出现在HTTP响应上,但与此HTTP响应相关联的HTTP请求当然没有Cookie。

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.

您基本上需要先发送重定向,以便在呈现HTTP响应期间可用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.

这篇关于了解JSF中的HttpServletRequest和cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆