Saturday 23 November 2013

How to Access Session Scope in ADF Model Layer

This below blog we will see how to access the session scope in ADF model layer or business components.

In real time, we need to access some environment variables across all the layers (Model layer and View-controller layer) of ADF application. Generally we store environment variables in session scope and through this variable we can access the values for the same session. Basically this session we are using in view-controller layer. Now we will see the same session from view layer, we can use in model layer also.

In this application we have two views, first one is Login and second is Success. In Login page we will give user name and password, if it correct then success page will comes up. In success page some control is there.
                                             

In login page action, setting the session variable and the code is mentioned below.
    public String doLogin() {
       // Add event code here...
       String uName = getUserNameId().getValue().toString();
       String pWd = getPassWordId().getValue().toString();
       FacesContext ectx = FacesContext.getCurrentInstance();
       HttpServletRequest request = (HttpServletRequest)ectx.getExternalContext().getRequest();
       HttpSession httpSession = request.getSession();
       httpSession.setAttribute("serverName", request.getServerName());
       httpSession.setAttribute("serverPort", request.getServerPort());
       System.out.println("In UI Layer username"+request.getServerName());
       if(uName.equalsIgnoreCase("prabhat") && pWd.equalsIgnoreCase("prabhat1")){
            return "login"; 
        }
        return null;
    }

In this above code the environment variable storing in a session variable. Now we need to get the same HTTP session variable from the ADF context in model layer. For getting the session variable, we need to override the prepareSession() method inside the implementation class. The code is mention below 

protected void prepareSession(Session session){
        Map sessionScope = ADFContext.getCurrent().getSessionScope();
        String serverName = (String)sessionScope.get("serverName")
        System.out.println("In Model Layer serverName"+serverName);
        super.prepareSession(session);
    }

Now you can run the application and give the username and password.
                                            
After submitting the login button, we can get the session variable inside the model layer
                                           
Thanks...

No comments:

Post a Comment