Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

I’m struggling to figure out how to use $http.get in AngularJS to pass filter parameters.

The URL is:

http://localhost:8080/template/users/query;username=abcd;firstName=ding...

The RestController looks like this:

@RequestMapping(value={"/users/{query}"}, method=RequestMethod.GET)
public ResponseEntity<List<User>> queryUsers(@MatrixVariable(pathVar="query") Map<String, List<String>> filters) {
  ....
}

When I access the above URL directly in my browser, everything works fine. However, when I try to call it using $http.get in AngularJS, it fails.

This is the AngularJS code I'm using:

this.searchUser = function() {
        var queryStr = '';
        for (var key in userObj.search) {
            if (userObj.search[key]) {
                queryStr += ";" + key + "=" + userObj.search[key];
            }
        }
        console.log('URL ', 'users/query' + queryStr);
        if (queryStr === "") {
            alert("No filters specified");
            return false;
        }
        $http.get('users/query', angular.toJson(userObj.search)).then(function successCallback(response) {
            if (response.data.errorCode) {
                console.log(response);
                alert(response.data.message);
            } else {
                console.log('Successfully queried for users ', response.data);
                userObj.users = response.data;
            }
        }, function errorCallback(response) {
            console.log('Error ', response);
            alert(response.statusText);
        });
    };

When calling this method, I receive the following error:

errorCode: 400
message: "Failed to convert value of type [java.lang.String] to required type [long]; nested exception is java.lang.NumberFormatException: For input string: "query""

I’ve even tried passing the query string as specified in the URL above, but the same error persists. It seems like the request isn’t reaching the RestController method at all.

How can I resolve this issue?

Answer №1

When using the get method, JSON cannot be passed directly.

If you want to pass JSON as a query string, you must prepare the object first.

var queryStr = {};
for (var key in userObj.search) {
    if (userObj.search[key]) {
        queryStr[key] = userObj.search[key];
    }
}

For your HTTP#GET call, it should look like this :

$http.get('users/query', {params: queryStr}).then(...

OR

$http({
    url: 'users/query', 
    method: "GET",
    params: queryStr
 });

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

Arranging HTML elements with jQuery - the existing script flips back and forth

I have created a code snippet on CodePen that showcases a feature of the website I am currently developing: http://codepen.io/barrychapman/pen/BzJGbg?editors=1010 Upon loading the page, you will notice 6 boxes. The first box is active, while the remaining ...

Coordinating a series of maneuvers

When it comes to coordinating multiple sequential actions in Redux, I find it a bit confusing. I have an application with a summary panel on the left and a CRUD panel on the right. My goal is to have the app automatically update the summary after a CRUD op ...

React TypeScript with ForwardRef feature is causing an error: Property 'ref' is not found in type 'IntrinsicAttributes'

After spending a considerable amount of time grappling with typings and forwardRefs in React and TypeScript, I am really hoping someone can help clarify things for me. I am currently working on a DataList component that consists of three main parts: A Co ...

The code to trigger the button with the ID 'Button' using Document.getElementById() is not executing the associated code-behind

Having just started coding in javascript/VB.NET, I am struggling to get my Button2 onClick event to work properly. The Code-Behind Click Event for Button1 in Page.aspx.vb: Protected Sub _lnbComments_Click(ByVal sender As Object, ByVal e As System.EventAr ...

Employing API Integration with Node.js and AngularJS

Currently in the process of developing a language translating messaging application using Node and Angular. I have decided to utilize the Yandex API since Google Translate is not free. You can find more information about the API at www.yandex.com I am unc ...

Having an issue with transmitting information to the database using ajax and Laravel

I am currently working on creating a drag and drop list that can be sorted. Each time an element is dropped into a new area, the order of the list should change accordingly. I am implementing this using AJAX and Laravel, but encountering an error when drop ...

Issue with component not updating upon state change

Having trouble getting my react function component to rerender immediately after updating the state. The application takes input for material cost of each product and calculates the total. I want the component to display the updated total as soon as the i ...

Having trouble with logging in/out, registration, and my submitPost function has suddenly ceased to work

Grunt is not showing any errors and when using the debugger "Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- user <- NavCtrl also "Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- user You can find the ...

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...

Guide to importing VRML Files with three.js

I am encountering an issue with importing a VRML file in three.js. Below is the content of the VRML file: #VRML V2.0 utf8 #Created by CINEMA 4D DEF B1 Transform { translation 600 0 0.333333 children [ DEF _60_ Transform { translation -600 0 0 ch ...

What is the best way to ensure that all the divs within a grid maintain equal size even as the grid layout changes?

I have a grid of divs with dimensions of 960x960 pixels, each block is usually 56px x 56px in size. I want to adjust the size of the divs based on the changing number of rows and columns in the grid. Below is the jQuery code that I am using to dynamicall ...

Issue with Protractor locating element even though everything appears to be in order

I'm having trouble locating this element with Protractor. It's really frustrating me. I double-checked in the dev console and the element definitely exists. Any suggestions on why it's not being found? <download path="api/backup_jobs/e ...

Expression fragment in Thymeleaf

In splitting my templates into head/main/footer parts using thymeleaf, I have found a method to include stylesheets and javascript on certain pages while excluding them from others. This is achieved through the use of fragment expressions outlined here. M ...

JQuery receives an enchanting response from the magic line

I could really use some assistance with this problem. I've managed to make some progress but now I'm stuck! Admittedly, my JQuery skills are not that great! Currently, I have a magic line set up where the .slide functionality is triggered by cli ...

What indicators should we look for to decide if JavaScriptExecutor is needed in a Selenium C# project?

Encountering an exception with TestInChrome1 - "OpenQA.Selenium.ElementNotInteractableException: element not interactable". On the other hand, using JavaScriptExecutor in TestInChrome2 resolves the issue. Some key questions arise: What is causing the ...

Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality. While researching, I came across a resource on how to vali ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

Changing the image source using Javascript and extracting part of the URL

i'm attempting to extract the image url from a series of urls in a loop, removing the hash portion () without the hash (?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDi79vN15idfFETvntyC9yat7FvZQ). I've managed to mak ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

Issues with Angular-Trix compatibility with Internet Explorer 10

I am currently using the Angular-trix rich text editor, which is functioning perfectly in all browsers including IE 11. However, I am encountering issues with it not working in IE10 or earlier versions. An error message that keeps appearing states: Una ...