0

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?

1

1 Answer 1

2

DON'T 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 of ways, 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!";
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reaction, when I try this method I get an error in my console. It says it cannot find the javaFunction in the directory where the jsp is in. I'm very new to Spring so I really appreciate the help here. errormessage:"POST localhost:8080/pages/javaFunction 404 (Not Found)"
uhm... I think it was my mistake, I copied ajax call with url what is not correct in this case, kindly check my update and let me know how it works
I still get the 404 error when I try this; "GET localhost:8080/pages/javaFunction?variable=VALUE 404 Not Found"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.