1

I want a controller with the following mapping (incomplete):

@GetMapping(/searchitems)
public @ResponseBody Page<Item> get(Item probe)

From the Item probe parameter I want to query by example in a repository of items and return the result.

Question:

How can I complete the mapping above for a search URL? As search URL I was thinking something like /searchitems?itemAttributeA=foo&itemAttributeB=bar&...itemAttributeZ=xyz. How can I tell spring to inject the passed request parameters into the Item probe fields with the same names?

hansi
  • 2,278
  • 6
  • 34
  • 42

3 Answers3

1

Adding @ModelAttribute should bind the individual request parameters into your Item POJO.

public @ResponseBody Page<Item> get(@ModelAttribute Item probe)
lane.maxwell
  • 5,002
  • 1
  • 20
  • 30
  • I want to add a follow-up. Spring has the concept of RestController, if you use this annotation instead of Controller, you can drop the ResponseBody annotation from your method signature – lane.maxwell Apr 20 '17 at 02:52
1

You can create a POJO and pass as a parameter in the controller class. Pojo should have the fields which you want to read and set. Spring will read and map those attributes in the Pojo which you will define as the request.

 @GetMapping(/searchitems)
 public ResponseEntity<List<Items>> searchItems(ItemRequest       itemRequest) {
 }

Only thing needs to be taken care is to check for binding result. If there are errors, we need to stop the request and handle or throw.

For e.g. All of the below attributes in the URL will be set in the Pojo.

https://domain/search-items?pageNumber=1&sortOrder=ascending&itemName=test&itemType=apparel&sortField=itemId&pageSize=5

denzal
  • 1,225
  • 13
  • 20
0

You can use @RequestParam for this.

public @ResponseBody Page<Item> get(@RequestParam("itemAttributeA") String itemAttributeA , 
                                    @RequestParam("itemAttributeB") String itemAttributeB,...)
Hadi J
  • 16,989
  • 4
  • 36
  • 62