how to pass javascript variable to Spring mvc controller

[亡魂溺海] 提交于 2020-01-24 07:06:22

问题


Could anyone please tell me how to get javascript variable value 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 countrySelection to controller


回答1:


You need to pass this variable as parameter from your post/get request to controller and the access it in controller like :

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

EDIT: If you are not using ajax and you want to sent extra parameter while form submission :

Add the variable in your form domain class with @Transient annotation so that spring wont look for matching element to your database table.

e.g.

@Transient
private String countrySelection;
//Setter getter methods

And then add form hidden variable in jsp like :

<form:hidden path="countrySelection"/>

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

In the controller you can access this string with objects getter method.



来源:https://stackoverflow.com/questions/17191373/how-to-pass-javascript-variable-to-spring-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!