我看过很多像我这样的帖子,但没有一个能帮助我。
这是我的托管 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>
过滤器:如果用户经过身份验证,则登录 Bean 不为空,并且会记录
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(登录 Bean)为空?
您是否确认使用了正确的 SessionScoped 注释?
看这里:JSF 登录过滤器,会话为空