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

0

Issue

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?

Solution

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

Answered By – IQbrod

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More