2015-03-13 116 views
0

我见过很多像我这样的帖子,但没有人能帮助我。从servlet过滤器获取Managed Bean(为空)

这是我的托管bean和它的sessionScoped,如果登录是确定它重定向到索引页面其他部分显示错误

@ManagedBean 
@SessionScoped 
public class LoginBean implements Serializable { 
/** 
* 
*/ 
private static final long serialVersionUID = 1L; 
private static final String[] users = {"anna:qazwsx","kate:123456"}; 

private String username; 
private String password; 

private boolean loggedIn  
public String doLogin() { 
    for (String user: users) { 
     String dbUsername = user.split(":")[0]; 
     String dbPassword = user.split(":")[1]; 

     // Successful login 
     if (dbUsername.equals(username) && dbPassword.equals(password)) { 
      loggedIn = true; 
      return "/tmpl/home/index.xhtml?faces-redirect=true"; 
     } 
    } 

    // Set login ERROR 
    FacesMessage msg = new FacesMessage("Login error!", "ERROR MSG"); 
    msg.setSeverity(FacesMessage.SEVERITY_ERROR); 
    FacesContext.getCurrentInstance().addMessage(null, msg); 

    return "/login/login.xhtml"; 
} 

public boolean isLoggedIn() { 
    return loggedIn; 
} 
} 

来看,一切正常这里,调用托管bean

的doLogin方法
<h:form id="login-form"> 
<h:messages /> 
<h:outputText value="Nom d'utilisateur:"/> 
<h:inputText value="#{loginBean.username}" id="username"/> 
<br/> 
<h:outputText value="Mot de passe:"/> 
<h:inputSecret value="#{loginBean.password}" id="password"/> 
<br/> 
<h:commandButton id="button" value="Login" action="#{loginBean.doLogin}" />  
<br/> 
</h:form> 

过滤:如果用户进行身份验证,则loginBean不为空,它的记录

public class LoginFilter implements Filter { 

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
    HttpSession session = ((HttpServletRequest) request).getSession(false); 
    LoginBean loginBean = (session != null) ? (LoginBean) session.getAttribute("loginBean") : null; 


    if (loginBean!=null) 
     System.out.println(loginBean.getUsername()); 

    if (loginBean == null || !loginBean.isLoggedIn()) { 
     System.out.println("here agai"); 
     String contextPath = ((HttpServletRequest)request).getContextPath(); 
     ((HttpServletResponse)response).sendRedirect(contextPath + "/login/login.xhtml"); 
    }   
    chain.doFilter(request, response);    
    } 
} 

为什么我的托管bean(loginBean)为空?

+0

与'@ javax.enterprise.context.SessionScoped'试试吧。 – alexander 2015-03-13 20:12:42

+0

@Alexander,实际上,正好相反。他使用JSF ManagedBean注释,所以他需要使用'javax.faces.bean.SessionScoped'。 – DavidS 2015-03-13 20:32:13

+0

谢谢你们,我没有导入javax.faces.bean.SessionScoped,我使用的是javax.enterprise.context.SessionScoped。 – jsf 2015-03-13 20:43:43

回答

1

您是否确认使用了正确的SessionScoped注释?

在这里看到: JSF login filter, session is null

+0

那实际上更多的评论,然后一个答案。我很快就会问这个问题。 – alexander 2015-03-13 20:08:13

+0

谢谢,我没有看到那篇文章,所以没有必要提出我的问题 – jsf 2015-03-13 20:44:15