-1

我开发了一个 Web 来从 login.xhtml 登录,但是当它验证用户不存在时,我在导航时遇到了问题。相反,该页面会引发异常(EJB NoResultException ,getsingle Result())。当我输入正确的用户名和密码时,应用程序可以正常导航,但是当用户不存在时会出现异常页面。我只是想实现,当用户输入错误的密码时,他会被重定向到 login.xhtml .我的代码看起来像这样

//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 异常。可能是什么问题,我希望它显示登录页面并显示错误密码或无效帐户的消息。使用 managedbean 作为 sessionscoped 登录的想法也是最佳实践吗?

4

1 回答 1

1

如果登录不正确,您的 EJB 似乎会引发异常,您可能需要捕获此异常并返回失败。

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 页面访问它。同样,由于每个用户会话都会发生一次,因此将其保持在会话范围内是有意义的。

于 2013-03-02T16:05:04.677 回答