Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

session

jsf

jsf-2

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

like image 854
Rajat Gupta Avatar asked Mar 31 '11 19:03

Rajat Gupta


1 Answers

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?
like image 140
BalusC Avatar answered Nov 15 '22 06:11

BalusC