10

I am attempting to @Inject a @SessionScoped bean into a Filter

@WebFilter("/*")
public class IdentityFilter implements Filter, Serializable {

    @Inject
    private LoginUser loginUser;
...

where LoginUser is @SessionScoped

The intention is for loginUser to represent the logged in user for the session.

The problem is it appears that I am not always getting the loginUser from the current session, I am getting 'leakage' between sessions as one session's LoginUser object is being shared with another session. Obviously this isn't good.

I am wondering if this is because the Filter object is a singleton, or at least reused between requests and sessions by the container (glassfish). (Right?)

Is there a better way to obtain the LoginUser object for the current session without using a property on the Filter?

2
  • Could you paste LoginUser code? If you don't have a non-private constructor with no parameters or the class is final or have a final method it will not work. Mar 8, 2012 at 18:37
  • Thanks Fabricio. I think this is ok, it does inject so must be. The problem is the sharing ... I think I found what's wrong, will post.
    – Jonathan
    Mar 11, 2012 at 21:53

1 Answer 1

13

My problem is that there is only one instance of the Filter in the container, effectively a singleton. It seems that CDI injects the first session level object into the Filter at first use and then the Filter stores that reference forever, even for other sessions.

I've found this solution, to inject a factory object (Instance) which I can use to get the session instance each time the Filter runs, i.e.

 @WebFilter("/*")
 public class IdentityFilter implements Filter, Serializable {

      @Inject 
      private Instance<LoginUser> loginUserSource;

And in

 @Override
 public void doFilter(...)
      LoginUser login   = loginUserSource.get();

This seems to fix my problem.

Thanks

2
  • 6
    Actually, CDI works using proxies and that´s not the actual LoginUser instance that gets injected as long it doesn´t have Dependent scope and meet the requirements from my first comment. Mar 12, 2012 at 14:24
  • 2
    +1 to Fabricio Lemos' answer. CDI provides proxies. This is mandated by the CDI specification (for all NormalScoped beans). Please make sure that the @SessionScoped you use really is the CDI one (javax.enterprise.context.SessionScoped) and NOT e.g. the one from JSF (java.faces.bean.SessionScoped). This is a common error and happens if your IDE just auto-imports the annotation from the wrong package. Those JSF Scopes are considered legacy since EE6 and might even get deprecated in future JSF versions.
    – struberg
    Oct 22, 2014 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.