过滤器中的@Inject不起作用

时间:2011-10-17 11:58:16

标签: dependency-injection java-ee-6 servlet-filters cdi jboss-weld

据我所知,CDI应该在过滤器中工作,但我无法让它为我工作。代码如下所示:

@WebFilter(filterName="authFilter",servletNames={"Faces Servlet"})
public class AuthFilter implements Filter {

    @Inject UserBean userBean;

    public AuthFilter() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        userBean.doSomething(); // Causes NullPointerException
        chain.doFilter(request, response);
    }
}  

UserBean.class

@Stateless
public class UserBean extends JPABean{
// Omitted
}

CDI已启用,如果我通过InitialContext.doLookup()或Servlet手动执行注入工作,如下所示:

@WebServlet(name = "MyServlet", urlPatterns = {"/MyPage"})
@ServletSecurity(@HttpConstraint(rolesAllowed={"somerole"}))
public class MyServlet extends HttpServlet {

    @Inject private UserBean userBean;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        userBean.doStuff(); // Works
        response.sendRedirect(request.getContextPath());
}

CDI不适用于过滤器吗?在那种情况下,为什么不呢?如果它应该,我可能做错了什么?

1 个答案:

答案 0 :(得分:3)

在此示例中,我将CODI @ViewAccessScoped bean(RegisterView)注入过滤器,在bean中设置属性并导航到使用该bean的视图。当页面加载时,我看到用户名设置为“fred”。这也适用于@SessionScoped(但不适用于@RequestScoped或@ViewScoped)。我认为线程安全需要动态注入,因为Web容器中只有一个过滤器实例,因此所有实例变量都是。

这个问题解决的问题是Faces Servlet在执行过滤器时没有运行,所以没有FacesContext。 getFacesContext()完成的聪明工作我从2004年开始直接从这个blog开始,我不知道是谁编写的,多年来没有添加任何内容,但如果有人知道让我知道!也许是他的BalusC 年轻的日子。它使用静态内部类来访问受保护的FacesServlet #setCurrentInstance()方法。

如果使用response.sendRedirect(),则无效。

package uk.co.myco.jsfbeans.helper;

import java.io.IOException;
import javax.enterprise.inject.Instance;
import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.inject.Inject;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uk.co.sportquest.entities.User;
import uk.co.sportquest.general.BaseClass;
import uk.co.sportquest.general.Log;
import uk.co.sportquest.jsfbeans.RegisterView;

/*
 * @author Brendan Healey
 * 
 * http://www.thoughtsabout.net/blog/archives/000033.html
 * 
 */

@WebFilter(filterName = "SocialAuthFilter", urlPatterns = {"/pages/socialAuthFilter.xhtml"},
dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE})
public class SocialAuthFilter extends BaseClass implements Filter {

    @Inject
    private Instance<RegisterView> rvDynamic;

    private ServletContext servletContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        servletContext = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        Log.log("testFilter: " + request.getPathInfo());

        FacesContext ctx = getFacesContext(req, res);

        RegisterView registerView;
        registerView = rvDynamic.get();

        User user = new User();
        user.setUserName("fred");
        registerView.setInputUser(user);

        FacesContext.getCurrentInstance().getExternalContext().redirect("/pages/register.xhtml");

    }

    @Override
    public void destroy() {
    }

    private abstract static class InnerFacesContext extends FacesContext {

        protected static void setFacesContextAsCurrentInstance(FacesContext facesContext) {
            FacesContext.setCurrentInstance(facesContext);
        }
    }

    private FacesContext getFacesContext(ServletRequest request, ServletResponse response) {
        // Try to get it first  
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (facesContext != null) {
            return facesContext;
        }

        FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
        LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
        Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

        // Either set a private member servletContext = filterConfig.getServletContext(); 
        // in you filter init() method or set it here like this:
        // ServletContext servletContext = ((HttpServletRequest)request).getSession().getServletContext();
        // Note that the above line would fail if you are using any other protocol than http

        // Doesn't set this instance as the current instance of FacesContext.getCurrentInstance 
        facesContext = contextFactory.getFacesContext(servletContext, request, response, lifecycle);

        // Set using our inner class
        InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);

        // set a new viewRoot, otherwise context.getViewRoot returns null
        UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "");
        facesContext.setViewRoot(view);

        return facesContext;
    }

}