-->

Java Web Application multiple user session handlin

2020-07-30 00:07发布

问题:

I use Glassfish server 3.1.1, and I successfully configured my realm for the usergroups.

While only 1 user is logged in, everything works fine, but as I log in with another account from a different browser (or even a different computer), the first session is cleared and the last logged in users data is shown in every previous sessions.

I'm using Netbeans, and I let it generate my entity classes from a postgreSQL database, then the JSF pages from the entities. I read about HttpSessions, but there wasn't everything clear to me. Shall I continue this way, or the solution is in a different direction? If this is the right way, could anyone send me a sample source?

Here is my code:

Login.xhtml:

<h:inputText id="email" size="25" value="#{login.email}" maxlength="30"/>
<h:inputSecret id="password" size="25" value="#{login.password}" maxlength="100"/>
<h:commandLink value="Bejelentkezés" action="#{login.loginAction}"/>

This is how my login class looks like:

@ManagedBean(name="login")
@RequestScoped
public class LoginBean
{

private String email;
private String password;

public String loginAction()
{
    HttpServletRequest req=(HttpServletRequest)FacesContext.getCurrentInstance()
            .getExternalContext().getRequest();
    try
    {
        System.out.println("login with: " + email + ", " + password + ".");
        req.login(email, password);
    }
    catch(ServletException e) ....

回答1:

The code posted so far looks fine.

but as I log in with another account from a different browser (or even a different computer), the first session is cleared and the last logged in users data is shown in every previous sessions.

This problem is caused elsewhere than in the code posted so far. The session should not be cleared at all. This is likely a misinterpretation of the happening. Perhaps you don't understand the concept "session". The symptoms indicate that you're apparently getting hold of the logged-in user in some static variable or an @ApplicationScoped managed bean. Make sure that you aren't doing that.

As to how the "session" works, please read this: How do servlets work? Instantiation, sessions, shared variables and multithreading.

As to how to choose the proper managed bean scope, please read this: How to choose the right bean scope?