What would be an effective method for sending a multitude of parameters to a controller?

I am currently working on an application that utilizes Java with the Spring framework and Javascript with AngularJs framework. The application features a table displaying a list of objects along with two text fields for filtering these objects. The filtering process occurs on the server side, where I pass the values from the text fields to the @RestController's method as parameters, and then to the repository method. On the 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;
    }

Dealing with just two filters is manageable, but what should be my approach if there are 10 or even 20 filters in play? Are there more efficient ways to handle this, like passing them as a Map or another method?

Answer №1

If you want to implement this Annotation @ModelAttribute, here's how you can do it:

@GetMapping("/data")
@ResponseBody
public List<Data> getDataWithFilters(@ModelAttribute Criteria criteria) {   
        List<Data> dataList = dataRepository.findByTypeAndCategory(criteria.type, criteria.category); 
        return dataList;
}

and Criteria.java

public class Criteria {
    public String type;
    public String category;
}

You can now access criteria.type and criteria.category in your controller

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I launch a URL when an ImageView is clicked in an Android app?

How to Create a Link from ImageView to a Web Page I attempted to implement the code provided in the link, both within and outside of the onCreate function in my main.java file. However, I have not been successful in getting it to work properly. Here is an ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

Retrieving historical data from a MySQL database to display in a div element

My main page features a button that opens a popup. Upon closing the popup, a script is triggered to call a PHP file for selecting data from the database. This selected data is then appended to a specific div within the main page: if (win.closed !== false ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Exploring the world of jQuery: Toggling radio buttons with variables on click

On the right side, there is a table of data that initially contains certain values, but can be modified using radio buttons and a slider on the left. If you select the first radio button for the "pay in full" option, it will increase the estimated discoun ...

Retrieve the structure from a React application

When it comes to documenting architecture, the process can be incredibly beneficial but also quite time-consuming and prone to becoming outdated quickly. I have come across tools like Doxygen that are able to extract architectural details such as dependen ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

Is there a Page Views tracker in sinatra?

Help needed with implementing a page views counter using Sinatra and Ruby. I attempted using the @@ variables, but they keep resetting to zero every time the page is reloaded... Here's an example: Appreciate any advice! ...

Exploring the capabilities of multiple nested controllers in AngularJS

I am facing a challenge that I haven't been able to find a solution for online. My search form includes multiple instances of a common controller used for typeahead/autocomplete searches. Each controller is set up with different parameters for search ...

What steps can be taken to identify the two highest numbers in an array, one being positive and the other

Seeking the optimal solution to resolve this issue Issue: Develop a function called ArrayChallenge (Javascript) that takes a single argument "arr" representing an array of numbers. The function should return the string true if there exist two numbers in t ...

React - Clearing State data retrieved from axios request

I am currently facing an issue with resetting the state of an object in my users array upon clicking the delete button. Even after successfully removing the object from the database, the state does not update as intended. I have managed to verify the prese ...

Experiencing a null pointer exception while using a RecyclerView's layout manager

Hey everyone, I'm facing a tricky error that I can't seem to figure out. Here's the issue: I keep getting this error message - java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Recycler ...

Secure your website against XSS attacks with DOMPurify

Currently I am working on resolving a cross-site scripting (XSS) vulnerability using DOMPurify. The issue lies in the URL provided below: https://stage-xyzmysite.com/login/?rUrl=javascript:alert('hi'). In order to create a proof of concept, I am ...

Create a script in Java or Python to determine the success or failure of the number of items present in a Navigation menu

I've encountered an issue while trying to determine the number of items (8 in total) in the navigation menu of . The logic doesn't seem to be executing correctly. It's possible that I'm using the wrong function or there is a mistake in ...

Refresh all tabs in the TabContainer

I have implemented multiple tabs using dojo on a web page, and I need to refresh the current tab every 5 seconds without refreshing the entire page. You can check out the code in this fiddle: http://jsfiddle.net/5yn2hLv9/4/. Here is an example of the code ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

An unexpected error has occurred within React Native, indicating that an object is

It's baffling why I keep receiving the error message: "undefined is not an object (evaluating '_this.props.navigation.navigate')" I am fairly new to react and have tried every possible solution but still cannot resolve this error. Belo ...

Stylus remains undefined even after a successful npm installation

I've been following a tutorial to learn more about node.js, but I keep encountering a strange error. After running npm install stylus, I receive the following output: npm http GET https://registry.npmjs.org/stylus npm http 304 https://registry.npmjs. ...