Search code examples
cdiservlet-filtersapache-tomeetomee-7

How to access @SessionScoped beans from @WebFilter


I am working on an AuthenticationFilter to redirect the user when he's not logged in. I am using TomEE 7.0.0-M2, so with Java-EE7 support.

AuthenticationFilter

@WebFilter(urlPatterns = "/*", dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.REQUEST})
public class AuthenticationFilter implements Filter {

@Inject
private LoginBean loginBean;
...

LoginBean

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@SessionScoped
public class LoginBean implements Serializable {

The problem is that the injected LoginBean is not the instance from the login.xhtml. So i can not verify if the user is successfully logged in.

The LoginBean is not in the session attributes, but i found the right loginBean here, but i have no idea how i can access it. But it looks like that the bean is in CDI but how can i access it from the WebFilter?


Solution

  • I still don't have an answer but an another solution that BalusC mentioned here:

    When the user is successfully logged i just add the loginBean manually to the sessionMap

    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("loginBean", this);
    

    In the WebFilter i access the loginBean with

    session.getAttribute("loginBean")
    

    Is this a good solution? I mean.. sounds like a workaround.