How to pass javascript variable to Spring mvc controller

Can someone tell me how to get the value of javascript variable in Spring MVC Controller.

var countrySelection = "Country Selection List:\n\n"; for (var i = 0; i < frm.selectedCountryItems.length; i++) if (frm.selectedCountryItems[i].checked){ countrySelection = countrySelection + frm.selectedCountryItems[i].value + "\n"; } alert(countrySelection); 

I want to pass the value of countrySelection to the controller

+4
source share
1 answer

You need to pass this variable as a parameter from your request to send / receive to the controller and access it in the controller, for example:

 @RequestMapping(...) public String getCountySelected(@RequestParam(value = "UR_PARAM_NAME") String param){ ... code goes here } 

EDIT: If you are not using ajax and want to submit an additional parameter while submitting the form:

Add a variable to the form domain class with the @Transient annotation @Transient that spring does not look up the corresponding element in the database table.

eg.

 @Transient private String countrySelection; //Setter getter methods 

And then add the hidden form variable in jsp, for example:

 <form:hidden path="countrySelection"/> 

And then set $("#countrySelection").value(countrySelection); using your jquery.

In the controller, you can access this line using the getter method of objects.

+4
source

Source: https://habr.com/ru/post/1487038/


All Articles