Using CDI injection in servlet

I'm trying @Inject a @SessionScoped bean in Filter

 @WebFilter("/*") public class IdentityFilter implements Filter, Serializable { @Inject private LoginUser loginUser; ... 

where LoginUser is @SessionScoped

It is assumed that loginUser will represent the registered user for the session.

The problem is that I do not always get LoginUser from the current session, I get a "leak" between sessions, since there is one session. The LoginUser object is sharing with another session. Obviously, this is not good.

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

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

+6
source share
1 answer

My problem is that there is only one filter instance in the container, effectively a singleton. It seems that CDI first injects the first level-level object into the filter, and then the filter keeps this link forever, even for other sessions.

I found this solution to introduce a factory object (instance) that I can use to get a session instance every time a filter is executed, 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

+8
source

Source: https://habr.com/ru/post/910209/


All Articles