0

Most of our filtering is done with @RequestBody and this is nice as it automatically maps all the fields that are sent in the post to an object we choose. We have had requests to allow a get and just pass parameters in the URL instead. It has been a bit of a battle supporting these guys the way we want, but in the end we have made the changes. The only problem is that it makes it pretty clunky (at least for my implementation.) I am looking for suggestions to make it cleaner and less manual.

Before:

    @RequestMapping(path = "forecast/filter", method = RequestMethod.POST)
List<FinancialContractData> forcastFilter(            
        @RequestBody(required = false) FinancialContractData filter) {

    filter = filter ?: new FinancialContractData()

    List<PortfolioContractInvoiceBook> curBooks = getPortContrInvBooks(filter)

After:

    @RequestMapping(path = "forecast/filter", method = [RequestMethod.POST, RequestMethod.GET])
List<FinancialContractData> forcastFilter(
        @RequestParam(value = "startDt", required = false) Date startDt,
        @RequestParam(value = "contractId", required = false) Integer contractId,
        @RequestParam(value = "differencesOnly", required = false) boolean differencesOnly,
        @RequestBody(required = false) FinancialContractData filter) {

    filter = filter ?: new FinancialContractData()

    filter.startDt = startDt ? new RBSDate(startDt.time).asCalendar(): filter.startDt
    filter.startDt = filter.startDt ?: defaultDate
    filter.contractId = contractId ?: filter.contractId
    filter.differencesOnly = differencesOnly ?: filter.differencesOnly

    List<PortfolioContractInvoiceBook> curBooks = getPortContrInvBooks(filter)

This particular SAP group only needs to filter by three of the properties that are on the object (there are quite a few more). Id love to generically map all params to properties on the object. I am leaning towards an advice on the controllers so that all of our methods would get this for free. Any other hidden gems in spring that I am not thinking of?

Chewy
  • 651
  • 6
  • 21

2 Answers2

0

It is possible to pass a model, if the model has the proper setters and getters:

forcastFilter(MyRequestModel model)

See: https://stackoverflow.com/a/16942352/5585182

Albert Bos
  • 2,012
  • 1
  • 15
  • 26
0

This seems to be the simplest solution for me right now.

    @RequestMapping(path = "forecast/filter", method = [RequestMethod.POST, RequestMethod.GET])
List<FinancialContractData> forcastFilter(
    @RequestBody(required = false) FinancialContractData filter, FinancialContractData paramFilter) {

filter = filter ?: paramFilter

List<PortfolioContractInvoiceBook> curBooks = getPortContrInvBooks(filter)

It still requires specifying two parameters and choosing one to use (i prioritize POST body), but it is pretty clean and does not clutter with merging data.

Chewy
  • 651
  • 6
  • 21