我开发了一个从login.xhtml登录的web,但是当验证用户不存在时我遇到了导航问题。相反,该页面会引发异常(EJB NoResultException,getsingle Result())。当我输入正确的用户名和密码时,应用程序导航正常,但是当用户不存在时它会带来异常页面。我只是想在用户输入错误的密码时尝试实现这一点,他被重定向到login.xhtml .my代码看起来像 这个
//managed bean class
//session scoped
private Admin ad = new Admin();
private String username;
private String password;
//string setters getters
// admin getters, setters
public String login(){
ad= adminEJB.verifyUser(
username,password);
If(ad!=null)
return="welcome";
else return ="login";
}
当我使用正确的用户名和密码登录时,它会完美地导航到welcome.xhtml页面,但是当我使用错误的密码进行测试时,它会向我显示错误页面Ejb noresult exception。可能是什么问题,我希望它显示登录页面,并显示错误密码或无效帐户的消息。还有一个想法是使用managedbean作为sessioncoped登录最佳实践吗?
答案 0 :(得分:1)
如果登录不正确,您认为EJB Thorw异常,您可能需要捕获此异常并返回失败。
private UIComponent component;
public UIComponent getComponent() {
return component;
}
public void setComponent(UIComponent component) {
this.component = component;
}
public String login(){
try{
ad= adminEJB.verifyUser(
username,password);
If(ad!=null)
return="welcome";
else {
FacesContext context = FacesContext.
getCurrentInstance();
context.addMessage(component.getClientId(),
new FacesMessage("Login Failed"));
return "login";
}
}catch(EJBException e){
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(component.getClientId(),
new FacesMessage(e.getMessage())); return "login";
}
}
然后在登录页面中使用<h:message>
来显示登录错误。
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:body>
<h:form>
<h:message for="login"/>
<h:commandButton id="login"
value="click me" action="#{componentMsgBean.doAction}"
binding="#{componentMsgBean.component}" />
</h:form>
</h:body>
</html>
会话Bean对于登录是一个好主意,因为您可以在用户会话中保存用户名和其他相关数据,如角色等,并从任何xhtml页面访问它。此外,每当用户会话发生一次时,将其保持在会话范围内是有意义的。