如何在应用程序上使用新的用户登录名创建新会话?

问题描述:

新用户登录应用程序后,如何在JSF 2.0中创建新会话?

How can I create a new session in JSF 2.0 as soon as a new User logs in on the application?

您不需要.精心设计的webapp毫无意义. servletcontainer已经进行了会话管理.只需将已登录的用户放在会话范围内即可.

You don't need to. It makes in well designed webapps no sense. The servletcontainer does already the session management. Just put the logged-in user in the session scope.

@ManagedBean
@RequestScoped
public class LoginController {

    private String username;
    private String password;

    @EJB
    private UserService userService;

    public String login() {
        User user = userService.find(username, password);
        FacesContext context = FacesContext.getCurrentInstance();

        if (user == null) {
            context.addMessage(null, new FacesMessage("Unknown login, try again"));
            username = null;
            password = null;
            return null;
        } else {
            context.getExternalContext().getSessionMap().put("user", user);
            return "userhome?faces-redirect=true";
        }
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "index?faces-redirect=true";
    }

    // ...
}

在同一会话的所有页面以及其他bean的@ManagedProperty中,登录用户都可以作为#{user}来使用.

The logged-in user will be available as #{user} in all pages throughout the same session and also in @ManagedProperty of other beans.

但是,注销后,使会话无效更为有意义.这也将破坏所有会话作用域的bean.您可以使用 ExternalContext#invalidateSession() .

On logout, however, it makes more sense to invalidate the session. This will trash all session scoped beans as well. You can use ExternalContext#invalidateSession() for this.

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "index?faces-redirect=true";
    }

另请参见: