0

我正在登录。问题是:我的 isUserLoggedIn() 方法被其他会话多次调用(我已经使用检查过 (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false))。

Login bean(一个 JSF 页面)是这样的:

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

有任何想法吗?谢谢你。

4

1 回答 1

1

回到那里一段时间后,我发现问题与 url 路径有关。cookie 是为路径生成的,当更改路径并尝试访问会话时,它又生成了另一个。

无论如何,我发现这绝对不是保护 Java EE 应用程序的方法(请参阅 Java EE 6 手册),所以我将采用其他方式。

谢谢。

于 2011-09-29T14:28:05.517 回答