Skip to content
Advertisement

What is a good way to pass many parameters to controller?

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement