开发者

Bind a set in a spring form

I am trying to bind a spring form with a set in the command object.

In my command class AInstance I defined set as

private Set<BParameter> bParameters = new HashSet<BParameter>();

In jsp I bind it as

<form:input path="bParameters " />
<form:input path="bParameters " />

As its a Java Set so there may be many fields开发者_如何学Python. When I submit this form I tried to get Set as:

Set<BParameter> bParameters = aInstance.getBParameters();

I got Set with a 0 size.

I also tried to bind as

<form:input path="bParameters[${itemsRow.index}].bParmvalues[0].parmValue" />

but got exception

Invalid property 'bParameters[0]' of bean class

What is the problem with my binding?


Use an List in the controller.

In the view you can use this straight html (not sure if this works with spring tags).

<input name="bParameters[{idx}].bParmvalues[0].parmValue" />


Its going to be an array, which Spring will translate into a List; it will also instantiate the List implementation - you don't need to do that in your Command object. Try using

private List<String> bParameters;

public void setBParameters(List<String> bParameters) {
    this.bParameters= bParameters;
}
public List<String> getBParameters() {
    return bParameters;
}

in your Command object. Those values are probably coming in as Strings.


I don't have problems binding as

 private Set<Types> typeses = new HashSet<Types>(0);


  <form:textarea path="typeses" style="width:200px;height:150px"/>

I use Spring 3.5. The only problem with this is, that it leaves []-marks on the field for some reason


I cannot find a way to bind Set into form parameters. However other solutions suggesting to "use list instead" is not good enough for me because if the field is part of JPA one-to-many relationship with eager fetching, using List will cause duplicates

Hence the best solution I find so far is by posting the form as JSON -- using Ajax -- instead. Here's how in JQuery:

var person = // .. construct form object here

$.ajax(url, {
  method : 'post',
  contentType : 'application/json',
  data : JSON.stringify(person)
});

Note that you need to mark the contentType as application/json

On the controller side, you can bind this to a Java object by using @RequestBody annotation:

@RequestMapping(..)
public void save(@RequestBody Person person) {
  ..
}

More info here: https://gerrydevstory.com/2013/08/14/posting-json-to-spring-mvc-controller/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜