1

这个问题与我最近发布的另一个问题有关:Understanding HttpServletRequest and cookies in JSF

为了实现记住我的登录JSF,我使用了一个 cookie 并读取它WebFilter。过滤器获取 cookie 并在 中设置 cookie 值SessionScoped ManagedBean,但由于某种原因ManagedBean无法在网页中显示它。

Filter 的doFilter实现:

@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("MyTestCookie")) {
                System.out.println("Filter got cookie: " + cookie.getValue());
                cookieBean.setValue(cookie.getValue());
            }
        }
    }
    chain.doFilter(request, response);
}

饼干豆类

@ManagedBean
@SessionScoped
public class CookieBean implements Serializable {

    private String value;

    @PostConstruct
    public void init() {
        System.out.println("Instantiated CookieBean");
    }

    public String getValue() {
        System.out.println("CookieBean returning Value: " + value);
        return value;
    }

    public void setValue(String value) {
        System.out.println("CookieBean getting Value: " + value);
        this.value = value;
    }

    public void create() {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        Map<String, Object> props = new HashMap<String, Object>();
        props.put("maxAge", 10000);
        ec.addResponseCookie("MyTestCookie", "Hello Cookie", props);
    }    
}

CookieBean cookieBean通过javax.inject.Inject注解的方式注入到过滤器中。

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: #{cookieBean.value}" /> 
</h:form>

第一个问题是,在设置 cookie 之后,如果我开始一个新会话(通过打开一个新的浏览器会话),网页不知道 cookie 值,因为在显示页面SessionScoped ManagedBean会更新。

问题1:如何及时检测cookie值以更新rendered网页中的某些属性?

第二个问题是,如果我通过按浏览器中的重新加载(或刷新)按钮重新加载网页,ManagedBean 实例与之前相同(该@PostConstruct方法未触发),但网页显示空 cookie值,服务器的输出中也显示了相同的值:

CookieBean returning Value: null
Filter got cookie: Hello Cookie
CookieBean getting Value: Hello Cookie

问题 2:a 怎么可能在SessionScoped ManagedBean没有被重新创建的情况下失去其属性?

4

1 回答 1

0

问题 1的答案:正如这个问题的已接受答案中所解释的,我只需要在支持 bean 中进行重定向。这会强制 JSF 生成一个包含 cookie 的新 GET 请求。假设请求页面是我的欢迎页面,我必须在我的cookieBean:

FacesContext.getCurrentInstance().getExternalContext().redirect("faces/index.xhtml");

好吧,这很好用,但完整的 URL 现在显示在地址栏中。如果有办法避免这种情况,我会进一步调查。

对问题 2 的回答SessionScoped cookieBean被有效地实例化了两次,一次是在部署期间,一次是通过过滤器。问题是我使用的是 JSF ManagedBean 并将其注入javax.inject.Inject注释。我已经通过javax.inject.Namedjavax.enterprise.context.SessionScoped注解将它变成了一个CDI Bean,并且注入现在运行良好。

于 2012-07-26T13:35:50.000 回答