What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller.

Despite my efforts, I keep receiving url = "" in the controller.

  1. What could be causing this issue?
  2. Is there a solution to successfully passing these parameters?

$scope.executeRequest = function(){
    var url = "http://"+$scope.data.serverIP+":"+$scope.data.serverPort;
    $http.post('/admin/executeRequest/',JSON.parse($scope.data.request),url).success(function(data){
        $scope.data.response = data;
    }).error( function ( data, status ) {
        $log.info("getting request object for api from server : failure");
        if ( status === 403 ) {
            $scope.show403( data );
        }
    });
};

@RequestMapping(value="/admin/executeRequest/",method=RequestMethod.POST)
@ResponseBody
public ProductCategoryResponse executeRequest(@RequestBody ProductCategoryRequest request, String url){

Answer №1

Include the URL in the URL parameters and embed $scope.data.request in the request body.

    $scope.submitRequest = function(){
        var url = "http://"+$scope.data.serverIP+":"+$scope.data.serverPort;
        $http.post('/admin/submitRequest?url=' + encodeURIComponent(url), $scope.data.request).success(function(data){
            $scope.data.response = data;
        }).error( function ( data, status ) {
            $log.info("retrieving request object for API from server: unsuccessful");
            if ( status === 403 ) {
                $scope.displayError403( data );
            }
        });
    };

Next, modify your Java controller as follows:

    @RequestMapping(value="/admin/submitRequest/",method=RequestMethod.POST)
    @ResponseBody
    public ProductCategoryResponse submitRequest(@RequestBody ProductCategoryRequest request, @RequestParam String url){

Refer to the Spring documentation for more information on @RequestParam.

Answer №2

@RequestMapping(value = {"/admin/executeRequest_parentcategories", "/admin/executeRequest_subcategories"}, method = RequestMethod.POST)
@ResponseBody
public ProductCategoryResponse executeProductCategoryRequest(@RequestParam(value = "url") String url,
        @RequestParam(value = "api") String api, @RequestBody ProductCategoryRequest request) {

and the AJAX call for this would look like:

var apiUrl = '/admin/executeRequest_parentcategories+'?url=http://'+$scope.data.serverIP+":"+$scope.data.serverPort+"&api="+$scope.data.apiSelected;
$http.post(apiUrl, JSON.parse($scope.data.request)).success(function(data){

A big thank you to Sohan for the guidance :)

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

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Different methods to retrieve content within a div that is located on a separate, included page

It's a bit tricky to come up with a title for this topic, but essentially, I'm trying to figure out how to get content from an included page into a specific div using HTML and PHP. Let me break it down: In the header.php file, we have the follo ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

What is the process for clearing the cache of a crawling URL?

Currently, I am operating a crawler that gets triggered through an expressjs call. However, whenever I make the same request again, the crawler runs once more but indicates that all routes have already been completed. I even went to the extent of deleting ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

Having difficulty retrieving additional arguments within createAsyncThunk when dispatched

When attempting to update the user thunk action by passing an axios instance as an extra argument, I am encountering difficulties in accessing the extra argument. Despite being able to access other fields such as getState</coode> and <code>disp ...

Verify the Absence of an Internet Connection Through a Popup on a Windows 10 Application Developed in Javascript

Hey there, I've been browsing the web but can't seem to find a comprehensive tutorial on how to write a code that displays an error message when there is no internet connection. I'm currently using Visual Studio to develop a Windows 10 App w ...

Exploring the possibilities of integrating jQuery into Firefox extensions

Can someone provide guidance on effectively implementing jQuery within a Firefox extension? My research has not yielded any up-to-date methods that address the latest version of jQuery, and I am aware that directly including it via script tag may lead to c ...

Updating Bootstrap Indicators with jQuery on Click Event

Unfortunately, I am unable to share an image due to limited internet data. My goal is to switch each image to its sprite equivalent. There are three list items that I'm struggling to change because they each have two classes that need to be updated. ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Provide the option to assign values on select options in order to choose specific JSON data

When working with JSON data from an API, I am creating a dynamic select element. The goal is to change some content (text and image src) based on the option selected from this select element. I have successfully populated the select options with names usi ...

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

How come the sound is played after the command is given?

function myTimer() { randint= Math.floor(Math.random() * 10)+1; randstimuli=gorilla.stimuliURL(dict[randint]); var audio = new Audio(randstimuli); audio.play(); var start=Date.now(); var ans=prompt("was the last number the same as t ...

Nested SetTimeout function fails to execute

Attempting to implement a button that provides feedback for its actions, I am faced with a challenge in Angular. After sending a put request to the server, the button's state changes to show this action. Upon receiving a response, the button's st ...

Locating a table in Java using Selenium without an ID

I am facing an issue with locating a table element in my code. The HTML structure looks like this: <table class="table"> <thead> <tr> <th>Role</th> <th>Description</th> <th> ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Is it possible to utilize a single template and dynamically fill it with content as needed?

Is there a method to utilize a single template and dynamically insert content into it? http://jsfiddle.net/cmckeachie/mtV62/light/ var routingExample = angular.module('FunnyAnt.Examples.Routing', []); routingExample.controller('HomeControl ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

Unable to adjust the height of an MP4 video to properly display within a Material Box in both landscape and portrait orientations

While I have been learning JavaScript React, I encountered an issue with positioning an MP4 movie. You can view the code in this Codesandbox If you check out the FileContentRenderer.jsx file, you will see that the html5-video is used for the MP4. The g ...