会话范围的JSF托管bean在servlet过滤器中始终为null

时间:2015-03-04 08:39:20

标签: jsf session jsf-2 servlet-filters managed-bean

我尝试创建一个像本教程中的Login过滤器:

http://www.itcuties.com/j2ee/jsf-2-login-filter-example/

如果我想打开安全网站,过滤器会将我定向到登录页面。但是当我按下登录按钮时,我再次看到登录页面。

我按照问题登录过滤器,在那里我尝试从会话范围获取loginBean。 loginBean始终为null。根据教程,由于注释@SessionScope,我的loginBean应该在会话中。

我的问题是:如何让我的loginBean进入会话?

Login.xhtml:

<h:form id="login-form">
      ...
    <h:commandButton id="button" value="Login" action="#{loginBean.doLogin}"/>
      ...
 </h:form>

LoginBean.java:

@ManagedBean(eager=true,name="loginBean")
@SessionScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 4067847760780243370L;  
private static final String[] userlist = { "fuh:fuh", "huf:1234" };
private String username;
private String password;
private boolean loggedIn;
@ManagedProperty(value = "#{navigationBean}")
private NavigationBean navigationBean;

public LoginBean(){}

public String doLogin() {
    String redirect = "";
    // Get every user from database 
    for (String user : userlist) {
        String dbUsername = user.split(":")[0];
        String dbPassword = user.split(":")[1];
        // Successful login
        if (dbUsername.equals(username) && dbPassword.equals(password)) {               
            loggedIn = true;                
            Log.write("Benutzer " + username
                    + " hat sich erfolgreich angemeldet!");     
        }
    }               

    if (loggedIn)
        redirect = navigationBean.redirectToWelcome();
    else           
        redirect = navigationBean.redirectToLogin();            

    return redirect;
}

LoginFilter.java:

public class Loginfilter implements Filter {    
private LoginBean loginBean;

@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
     HttpServletRequest req = (HttpServletRequest)request;
     HttpServletResponse res = (HttpServletResponse)response;
     HttpSession session = req.getSession(true);

     //this is always null
     loginBean = (LoginBean) session.getAttribute("loginBean");

    if (loginBean == null || !loginBean.isLoggendIn()) {
        if (loginBean == null) {
            Log.write("loginBean null");
        }else if (!loginBean.isLoggedIn()) {
            Log.write("loginBean not logged in");
        }
        String contextPath = req.getContextPath();
        res.sendRedirect(contextPath + "/login/login.xhtml");
    }else{
        chain.doFilter(request, response);
    }
}

0 个答案:

没有答案