Y Zwen
Y Zwen

Reputation: 1

In spring mvc how do I get a javascript var as parameter in a java function?

I'm working on a jsp page and I need a Javascript variable as parameter inside a java function e.g.:

<script>
    function example(string){
        <% javaFunction(string); %>
    }
</script>

how can I pass the javascript String variable to the java fucntion?

Upvotes: 0

Views: 995

Answers (1)

Jordi Castilla
Jordi Castilla

Reputation: 26961

DONT USE SCRIPTLETS IN JSP!.


You must understand jsp (views) code is executed in client side, java one is at server (host) one.

In order to get variables from the host side, you have plenty vays, but for small things best option is to make an ajax call:

$.get( "javaFunction", 
   { variable: "VALUE" } 
).done(function( data ) {
   alert("Java function returned " + msg);
});

In java you need to map the url:

@RequestMapping(value = "/javaFunction", method = RequestMethod.POST)
public
@ResponseBody
String javaMethod(@RequestParam("variable") String variable) {

    if (variable.equals("VALUE") {
        return "Correct call!";
    } else {
        return "Mistake!";
    }
}

Upvotes: 2

Related Questions