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

后端 未结 1 1976
盖世英雄少女心
盖世英雄少女心 2020-12-28 23:39

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

1条回答
  •  死守一世寂寞
    2020-12-29 00:07

    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 讨论(0)
提交回复
热议问题