Monday, September 5, 2011

Implementing Login form in ADF

If we need to provide our own JSF login page then we can use following JSF code and corresponding managed bean code :

JSF Code:


<af:panelFormLayout id="pfl1">
                    <af:message for="loginname" partialTriggers="cb1" />
                    <af:inputText label="Login Name" id="loginname" />
                    <af:inputText label="Password" id="password" />
</af:panelFormLayout>

<af:panelGroupLayout id="pgl2">
                    <af:commandButton text="Submit" id="cb1" actionListener="#{MyApp_ManagedBean.Login}"/>
                    <af:commandImageLink text="SignUp" id="cil1"/>
</af:panelGroupLayout>



Managed Bean Code:


  public void Login(ActionEvent actionEvent) {
    FacesContext fctx=FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest)fctx.getExternalContext().getRequest();
    HttpServletResponse response = (HttpServletResponse)fctx.getExternalContext().getResponse();
    UIViewRoot viewRoot=fctx.getViewRoot();
    RichInputText userName = (RichInputText)viewRoot.findComponent("pt1:loginname"); 
    //pt1 indicated the page template naming container.
    String userNameStr = (String)userName.getValue();
    RichInputText password = (RichInputText)viewRoot.findComponent("pt1:password");
    String passwordStr = (String)password.getValue();
    try
    {
      int authSuccess=ServletAuthentication.login(userNameStr,passwordStr,request,response);  
      if(authSuccess==ServletAuthentication.AUTHENTICATED)
      {
        try{
          ExternalContext ectx=fctx.getExternalContext();
         //Using Controller Context  is recommended to implement redirect logic instead of directly calling  //External Context redirect method and passingredirect URL in it "faces/RedirectPage".
          ControllerContext controllerCtx = null;
          controllerCtx = ControllerContext.getInstance();
          String activityURL = controllerCtx.getGlobalViewActivityURL("WelcomePage");
          ectx.redirect(activityURL);


        }catch(IOException ioex){ioex.printStackTrace();}
      }
    }
    catch(LoginException loginex)
    {
      String message="Authentication Failed. Please try again";
      fctx.addMessage("pt1:loginname", new FacesMessage(FacesMessage.SEVERITY_ERROR,message,null));
    }
  }
}


Recommended Reading: Oracle Fusion Developer Guide Building Rich Internet Applications with Oracle ADF Business Components and Oracle ADF Faces

No comments:

Post a Comment