binding form variables with Model in springmvc

Even if springmvc provides @ModelAttribute, it could only bind name that not start with root variable name, for instance:

Model:

1
2
3
4
5
6
7
8
9
10
11
12
13
class OrderLog
{
private Client client;
private Restaurant restaurant;
}
class Client
{
private Integer cid;
}
class Restaurant
{
private Integer rid;
}

Action class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Controller
@RequestMapping(value = "/order")
public class OrderAction
{

private static final Logger LOG = LoggerFactory.getLogger(OrderAction.class.getName());

@Autowired
private OrderLogService orderLogService;

@Autowired
private ClientService clientService;

@Autowired
private RestaurantService restaurantService;

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Object create(@FormModel("orderLog") OrderLog orderLog)
{
orderLog.setClient(clientService.findById(orderLog.getClient().getCid()));
orderLog.setRestaurant(restaurantService.findById(orderLog.getRestaurant().getRid()));
orderLogService.save(orderLog);
return new Message("SUCCESS", "Ordered");
}
}

Without any specified assistance, one could only bind variables below onto OrderLog object.
curl -d"restaurant.rid=1&client.cid=2" "localhost:8080/order"
It did not includes root name: orderLog, makes it not easy and cosy enough to be binded onto a specified model, at the meantime, makes it harder for maintemance.


solution

After Googling, I found a great solution and assist.
By adding @formModel annotation and related resolving methods, springmvc now could tackle with it with great convenience.
While in integration, you need to register the customized arguments resolver into springmvc framework by add them in springmvc-servlet.xml to prevent potential risks.

1
2
3
4
5
6
<mvc:annotation-driven  content-negotiation-manager="contentNegotiationManager">
<mvc:argument-resolvers>
<bean class="rugal.common.springmvc.method.annotation.RequestJsonParamMethodArgumentResolver"/>
<bean class="rugal.common.springmvc.method.annotation.FormModelMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>

Now let us use:
curl -d"orderLog.restaurant.rid=1&orderLog.client.cid=2" "localhost:8080/order"

Everything runs smoothly! great!


binding form variables with Model in springmvc
https://rug.al/2014/2014-04-09-binding-form-variables-with-model-in-springmvc/
Author
Rugal Bernstein
Posted on
April 9, 2014
Licensed under