Search code examples
javaspringframeworksmodelattribute

Spring Framework - Multiple ModelAttributes of Same Type


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.


Solution

  • 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