简体   繁体   中英

How to keep a bean alive for the through session accessible from filter and EJB

I am trying to set a property to a bean ModelBean in a Filter and access this property in a JSF controller IndexController .

The ModelBean is annotated @SessionScoped and it is used in the filter and controller with @Inject . The problem is that two separate instances are created and I cannot access the property that I set in filter.

What would be the best way to keep the bean alive throughout the session? Or maybe there is a better method to pass data from the filter?

@SessionScoped
public class ModelBean{
    private String deviceId;

    public ModelBean() {
        super();
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }
}
@Provider
public class AuthRequestFilter implements Filter {

    @Inject
    ModelBean model;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {

        // the device id is set just fine
        model.setDeviceId(deviceId);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
}
@Named(value = "indexController")
public class IndexController {

    @Inject
    ModelBean model;

    // the method **is* called from the xhtml
    public String justAnExample() {
        // this is the problem, the deviceId is null=>
        return model.getDeviceId();
    }
}

Thanks to @Kukeltje for the suggestion to look into the packages. I still Don't know why the package javax.faces.bean.SessionScoped that I was using did not keep the bean alive, but replacing it with javax.enterprise.context.SessionScoped did the trick. The bean is now alive and the data can be passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM