How to use @SessionScoped with Guice

Hi
I'm currently playing with Guice and @SessionScoped. To give them more meaning, I decided to build a (very simple) authentication process.

Below I will explain each step that I have taken. Then I will ask you some questions.

[1] I created an Identity class that represents a person (guest or user):

@SessionScoped
public class Identity implements Serializable
{
    private String uid;
    private String name;

    public boolean isAuthenticate()
    {
        return uid != null;
    }

    public void logout()
    {
        this.uid = null;
    }

    /*Setters-Getters*/
}

[2] Then I created an authentication class that logs into the system:

public class Authentication
{
    @Override
    public Identity authenticate(String login, String password)
    {
        /*some code*/

        Identity identity = new Identity();
        identity.setUid(user.getId());
        return identity;
    }
}

[3] Then in my servlet I register the user:

@RequestScoped
public class LoginAction
{
    @Inject
    Injector injector;

    protected void login(HttpServletRequest req, HttpServletResponse resp)
    {
            Identity identity = injector.getInstance(Identity.class);
            Authentication auth = new Authentication();
            identity = auth.authenticate("login","password");
    }
}

[4] Finally, I create a filter that shows me if the user is authenticated:

@Singleton
public class SecurityFilter implements Filter
{
    @Inject
    private Injector injector;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)
    {
        Identity identity = injector.getInstance(Identity.class);

        if(identity.isAuthenticate())
        {
            System.err.println("USER");
        }
        else
        {
            System.err.println("GUEST");
        }

        chain.doFilter(request, response);
    }
}

Well, this code does not work. My uid is always "null".

Go to the questions:

a - , ?
b - @SessionScoped HttpSession?
c - Identity ( ) (http) ?

d - , @SessionScoped?

,
.

+5
1

[a] Identity LoginAction, , Guice. , uid name Identity, Guice.

,

identity = auth.authenticate("login","password"); 

:

Identity identity = injector.getInstance(Identity.class);
Authentication auth = new Authentication();
Identity authenticated = auth.authenticate("login","password");
identity.setUid(authenticated.getUid());
identity.setName(authenticated.getName());

, .

[b]/[d] : @SessionScoped HttpSession, , . , , .

[c] , , , , , - .

, :

  • SessionScoped, Identity, , Identity. , concurrency, .
  • Provider Injector ( ), Guice.
  • . ( / ).
+9

All Articles