简体   繁体   中英

Pass Map value to Spring MVC controller using <form:hidden>

On submitting the page, i need to do some process and send some data to the controller. I felt the 'Map' suits for my requirement to pass in the data. Here is what i am doing:

JSP:

<form:hidden id="passMapData" path="passMapData"/>

Controller:

@RequestMapping(value = "/newPage/testData", method = RequestMethod.POST)
public String newPageTestData(@Valid @ModelAttribute("npf") NewPageForm npf, BindingResult result, Model model) {

}

NewPageForm.java:

public class NewPageForm {
  private Map<String, String> passMapData = null;

  public Map<String, String> getPassMapData() {
    return passMapData;
  }

  public void setPassMapData(Map<String, String> passMapData) {
    this.passMapData = passMapData;
  }
}

Issue:

On submitting the form, the BindingResult in the controller is showing error "IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Map]"

Cant we pass a Map type to controller in form submit?

<form:hidden id="passMapData" path="passMapData"/> is used to pass the hidden String data. Basically it is a hidden field like <input type='hidden'/> in html.

You cannot pass the HashMap here,So your NewPageForm.java must be ,

public class NewPageForm {
  private String passMapData = null;

  public String getPassMapData() {
    return passMapData;
  }

  public void setPassMapData( String passMapData) {
    this.passMapData = passMapData;
  }
}

Note : If you need to pass the HashMap to the controller , just set the Hashmap in to the request of the JSP ,

request.setAttribute("passMapData",Your HashMap);

You can able to get the same Hashmap in the controller as ,

request.getAttribute("passMapData");

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM