这个问题与我最近发布的另一个问题有关: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
没有被重新创建的情况下失去其属性?