【发布时间】:2011-08-23 19:27:13
【问题描述】:
我正在登录。问题是:我的 isUserLoggedIn() 方法被其他会话多次调用(我已经使用
(HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false))。
(JSF 页面的)Login bean 是这样的:
@Named
@SessionScoped
public class Login implements Serializable {
@Inject
private Credentials credentials;
private UserData user;
public String login() {
if (this.credentials.getUsername().equals("daniel")) {
user = new UserData("Daniel");
return "success";
}
return "failure";
}
public boolean isUserLoggedIn() {
return user != null;
}
public String logout() {
user = null;
((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).invalidate();
return "success";
}
public String getUsername() {
return getUser() == null ? "" : getUser().getUsername();
}
@Produces
public UserData getUser() {
return user;
}
}
所以,发生的事情是:当 login() 被调用时,我可以通过 getSession() 看到它是 X,但是随后在尝试访问另一个页面时,当调用 isUserLoggedIn() 时,getSession() 方法返回 Y 而不是 X,并且用户属性为空。 isUserLoggedIn() 方法经常被调用多次,只有 1 个请求,每次调用它的会话都会改变。
顺便说一下,我用的是JBoss AS7 Final,我的faces-config.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-action>#{login.login}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/secured/home.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-action>#{login.login}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/*.xhtml</from-view-id>
<navigation-case>
<from-action>#{login.logout}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
</faces-config>
有什么想法吗?谢谢。
【问题讨论】:
-
如果您不进行一些调试工作,这个问题实际上是无法回答的。关键是您的客户端不支持 cookie,或者您在每个请求上都重新创建会话。第一步是使用像 Firebug 这样的 HTTP 流量检查器检查会话 cookie 会发生什么。服务器是否在每次响应时都返回一个新的
Set-Cookie?还是客户拒绝在每个请求上返回Cookie?这应该有助于确定罪魁祸首。 -
感谢您的回答,Balusc。回到那里一段时间后,我发现问题与 url 路径有关。 cookie 是为路径生成的,当更改路径并尝试访问会话时,它又生成了另一个。
标签: session jsf cdi session-scope