开发者

How can I create a new session with a new User login on the application?

How can I create a new session in JSF 2.0 as soon as a new User开发者_JAVA技巧 logs in on the application?


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";
    }

    // ...
}

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

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";
    }

See also:

  • How do servlets work? Instantiation, sessions, shared variables and multithreading
  • How to handle authentication/authorization with users in a database?
  • How to choose the right bean scope?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜