Spring Framework - Multiple ModelAttributes of Same Type

无人久伴 提交于 2019-12-08 07:42:38

问题


I am working on a checkout page that requires a shipping address and a billing address. This integrates with a third-party library which has these both implemented as the same type: Address. What I need to be able to do is something like:

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Response createOrder(
    @ModelAttribute("customer") Customer customer,
    @ModelAttribute("shipping") Address  shippingAddress,
    @ModelAttribute("payment")  Payment  paymentInformation,
    @ModelAttribute("billing")  Address  billingAddress
) {
    // Create the order
}

I am stuck on how to send two separate models of the same exact type over to my Spring application in a way that makes this work. I could potentially make facade models and map them to the real ones inside of the controller, but I would prefer not to go down that route if I can avoid it.

Edit: Changed the model attribute names to hopefully make the problem area more clear.


回答1:


Instead of creating separate model attributes for each type, create an Order object and model attribute 'order.'

 //Order class
 private Customer customer;
 private Address  shippingAddress;
 private Payment  paymentInformation;
 private Address  billingAddress

..

public Response createOrder(
    @ModelAttribute("order") Order order) {
    // Create the order
}

Then the request would look like

shippingAddress.city=foo&billingAddress.city=bar


来源:https://stackoverflow.com/questions/37467510/spring-framework-multiple-modelattributes-of-same-type

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