这个问题与我最近发布的另一个问题相关:Understanding HttpServletRequest and cookies in JSF .
为了在 JSF
中实现记住我登录,我使用了 cookie 并在 WebFilter
中读取它。过滤器获取 cookie 并在 SessionScoped
ManagedBean
中设置 cookie 值,但由于某种原因 ManagedBean
无法将其显示在网页。
过滤器的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);
}
CookieBean 类:
@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
注解的方式注入(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 后,如果我启动一个新 session (通过打开新的浏览器 session ),网页将不知道 cookie 值,因为 SessionScoped
ManagedBean
在页面显示后更新。
问题1:如何及时检测cookie值以更新网页中的某些rendered
属性?
第二个问题是,如果我通过按浏览器中的重新加载(或刷新)按钮重新加载网页,则 ManagedBean 实例与以前相同(@PostConstruct
方法是' t 已触发),但网页显示了一个空 cookie 值,并且服务器的输出中也显示了相同的值:
CookieBean returning Value: null
Filter got cookie: Hello Cookie
CookieBean getting Value: Hello Cookie
问题 2:SessionScoped
ManagedBean
怎么可能在不重新创建的情况下丢失其属性?
最佳答案
问题 1 的回答:如已接受的答案中所述 question ,我只需在支持 bean 中进行重定向即可。这迫使 JSF 生成一个包含 cookie 的新 GET 请求。假设请求页面是我的欢迎页面,我必须在我的 cookieBean
中编写以下内容:
FacesContext.getCurrentInstance().getExternalContext().redirect("faces/index.xhtml");
嗯,这很好用,但完整的 URL 现在显示在地址栏中。我将进一步调查是否有办法避免这种情况。
问题 2 的回答:SessionScoped
cookieBean
被有效实例化两次,一次在部署期间,一次由过滤器实例化。问题是我使用的是 JSF ManagedBean 并使用 javax.inject.Inject 注释注入(inject)它。我通过 javax.inject.Named
和 javax.enterprise.context.SessionScoped
注释将其设为 CDI Bean,并且注入(inject)现在运行良好。
关于java - 用于处理“记住我”登录的 WebFilter、EL 和 SessionScoped ManagedBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11637615/