Tuesday, 11 June 2013

ADF : Running or calling javascript from java bean

In the other post of mine I wrote about the steps to call Java method from a javascript code. Now I am gonna tell you how we can call a Javascript code from Java code. This is the easiest method I found on the internet.
  1. For calling Javascript you have to use the following method in the java bean :

    public static void runJavaScriptCode(String javascriptCode) { 
             FacesContext facesCtx = FacesContext.getCurrentInstance(); 
             ExtendedRenderKitService service =
    Service.getRenderKitService(facesCtx, ExtendedRenderKitService.class); 
             service.addScript(facesCtx, javascriptCode); 
           } 



    You have to import the following packages :
    import javax.faces.context.FacesContext;
    import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
    import org.apache.myfaces.trinidad.util.Service;
  2.  And to call the javsccript from the java code :
    runJavaScriptCode("alert(\"My name is Java\");");

ADF : Calling Java code from JavaScript

There are occassions on which we need to call Java code that resides in the bean from the client side script i.e. Javascript. Here are the steps to do so.

  1. Use the given code to create a inputtext component in ADF page. You need to add a clientListener and a serverListener as given in code snippet.

    <af:inputText label="Label 1" id="it1">
                        <af:clientListener type="keyUp" method="handleBlur"/>
                        <af:serverListener type="MyCustomServerEvent" method="#{DateBean.handleServerEvent}"/>
                    </af:inputText>

    <af:resource type="javascript">
                    function handleBlur(evt) {
                   
                    var inputTextComponent = evt.getSource();
                    AdfCustomEvent.queue(
                            inputTextComponent,
                            "MyCustomServerEvent",{fvalue:inputTextComponent.getSubmittedValue()},
                            true
                            );
                            evt.cancel();
                    }
    </af:resource>


    • Here the code var
      " AdfCustomEvent.queue(inputTextComponent,"MyCustomServerEvent",{fvalue:inputTextComponent.getSubmittedValue()},true); "

      is like


      AdfCustomEvent.queue(
      Source component
      ,
      the type defined in servetlistener
      ,
      key value pair,
      immediate(
      true or false)
      );
  2. Now create a class that will contain the method that is called from the javascript. Here i have named it DateBean.
    And create a method as shown.

        public void handleServerEvent(ClientEvent ce){
            String message = (String) ce.getParameters().get("fvalue");
            System.out.println(message);
    }
  3. Now run the code. The server side java method is called on onblur event on the input field.