0

I have an application on Java (Spring framework) and Javascript (AngularJs framework). There are list of objects in the table and two text fields for filtering this objects. Filtering happens on the server side so I pass these values from text fields to @RestController's method as params and then to the repository method. Client side:

        $http({
            method: 'GET',
            url: '/messages',
            params: {sender: $scope.sender, recipient: $scope.recipient}
        }).then(
            function (res) {
                $scope.messages = res.data;
            },
            function (res) {
                console.log("Error: " + res.status + " : " + res.data);
            }
        );

Server side:

    @GetMapping("/messages")
    @ResponseBody
    public List<Message> getMessagesWithFilters(@RequestParam(required = true) String sender,
                                                @RequestParam(required = true) String recipient) {
      
        List<Message> messages = messageRepository.findBySenderNumberAndRecipientNumber(sender, recipient); 
        return messages;
    }

It's pretty easy when there're only two filters but what should I do if there are 10 or 20 of them? Is there a good way to do this, should I pass them as Map or something like that?

  • Try this: https://medium.com/@AADota/spring-passing-list-and-array-of-values-as-url-parameters-1ed9bbdf0cb2 – locus2k Sep 21 '20 at 15:47
  • Aditionally, you can use `@RequestParam MultiValueMap params`, which would give you a `Map` where the key is the param name, and the value is a `List` of all the values given for that param. – BeUndead Sep 21 '20 at 15:48
  • [This post and its answer](https://stackoverflow.com/questions/16942193/spring-mvc-complex-object-as-get-requestparam) may be interesting aswell. – Turing85 Sep 21 '20 at 15:50
  • @locus2k thanks but I need to be able to define what filter was passed, it's not very convenient to do with this method – mech_heart Sep 21 '20 at 15:55
  • @BeUndead I was just thinking about it, thank you – mech_heart Sep 21 '20 at 16:07

1 Answers1

1

You may use this Annotation @ModelAttribute like :

@GetMapping("/messages")
@ResponseBody
public List<Message> getMessagesWithFilters(@ModelAttribute Filter filter) {   
        List<Message> messages = messageRepository.findBySenderNumberAndRecipientNumber(filter.sender, filter.recipient); 
        return messages;
}

and Filter.java

public class Filter {
    public String sender;
    public String recipient;
}

You might then use filter.sender and filter.recipient in your controller

IQbrod
  • 2,060
  • 1
  • 6
  • 28