Grails 3 UrlMappings

356 Views Asked by At

How do you map a Url with two ids:

/orders/$id1/orderlines/$id2

The id2 is optional

/orders/$id1/orderlines GET -> all orderlines for order id1 /orders/$id1/orderlines/$id2 GET -> show orderline id2 within order id1

The methods are to be mapped to OrderLineController

It is pretty easy with Spring MVC @RequestMapping and @PathVariable.

Grails 3 does not allow @RequestMapping (there are are tricks to make it work - but I don't want to go that route - needlessly complex).

Appreciate the help. I did quite a bit of googling.

2

There are 2 best solutions below

1
On

You can use UrlMappings:

UrlMappings.groovy

 class UrlMappings {
        static mappings = {
            "/orders/$id1/orderlines"(controller: 'orderLine', action: 'someAction1')
            "/orders/$id1/orderlines/$id2"(controller: 'orderLine', action: 'someAction2')
        }
    }

OrderLineController.groovy

def someAction1(Long id1){
  //...
}
def someAction2(Long id1, Long id2){
  //...
}
1
On

Using nested URLMappings:

UrlMappings.groovy

class UrlMappings {
  static mappings = {
    "/orders"(resources:"order") {
      "/orderLines"(resources:"orderLine")
    }
  }
}

OrderController.groovy

def show() {
  params.id // Order.id
}

OrderLineController.groovy

def show() {
  params.orderId // Order.id
  params.id      // OrderLine.id
}

As stated by @dmahapatro, check out the documentation on Nested Resources.