Search code examples
javascriptstruts2velocity

To invoke java function from velocity template during onclick event


Web application uses struts2 and velocity

1)

The velocity file has a link and when the link is clicked i want java function to be called.

productform.vm


 <a href="javascript:void(0);" onclick="*************" id="acnt_link"> Add Acnt </a> 

when the link from velocity file is clicked, i need java function to be called

abc.java

public void printabc(){
syso("Java function called when link from velocity temp is clicked");
}

Please advise on how to do this

2)

i can invoke javascript function when link from velocity is clicked, but from javascript function how can i call the java function(for example abc.printabc())

Please advise.


Solution

  • You can take a look at DWR which gives you methods from java as javascript function. Directly taken from their Tutorial:

    public class Remote {
        public String getData(int index) { ... }
    }
    

    And the correspondening html snippet:

    <head>
    <!-- other stuff -->
    <script type="text/javascript" src="[WEBAPP]/dwr/interface/Remote.js"> </script>
    <script type="text/javascript" src="[WEBAPP]/dwr/engine.js"> </script>   
    <script>
    function myRemoteMethod() {
        Remote.getData(42, {
            callback: function(str) { 
                alert(str); 
        }});
    }
    </script>
    </head>
    <body>
    <!-- ... -->
        <a href="javascript:void(0);" onclick="myRemoteMethod()">Add Acnt</a>
    <!-- ... -->
    </body>
    

    Make sure you integrate the DWR into struts, they have also tutorials for that: DWR Struts Tutorial.

    Another solution would be to call that java method via an ajax request:

    function myRemoteMethod() {
        $.get('/link/to/method/')
        .done(function (data) {
             alert('Return message of server was:' + data);
        });
    }
    

    This is a jQuery example, so make sure you have the library in the <head> of your html code. Call this method in the html code and you "call" the java method via ajax.

    <a href="javascript:void(0);" onclick="myRemoteMethod()">Add Acnt</a>