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

What steps can I take to enable ads in Chrome within my automation script?

Looking to implement a Google login scenario, Begin by opening the website and clicking on the "Login with Google" option A Google popup will appear prompting you to enter your email, password, and then click on login Expected outcome: Successfully loggi ...

Simulating NextJS router triggers using Jest

I've been attempting to simulate NextJS router events using Jest. I came across a useful resource at NextJS router & Jest. The approach outlined there closely resembles mine. Unfortunately, the solution provided in that post is not yielding the d ...

Tips for showcasing a "loading" animation as a lazy-loaded route component loads

Utilizing webpack's code splitting feature, I have divided my application into multiple chunks to prevent the entire bundle from being downloaded at once when a user visits my website. Some routes require large chunks that may take some time to downl ...

Is it possible to retrieve data from a database using jQuery and store it in separate variables?

I am able to print out one field from a table, but I want to display all fields in separate tables. How can I achieve this? Below is my save/load code: // Save/Load data. $('').ready(function() { if($.cookie('code')) { $.aj ...

Angular is unable to bind with 'dragula' because it does not recognize it as a valid property of 'ul'

I've been attempting to incorporate dragula into my Angular 2 application, but I'm struggling to get it functioning. This is what I have added in my app.module.ts file: import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

Exploring the Power of BufferGeometry and Textures in Three.js

I am experiencing an issue where the texture does not show up when I try to load textures on a THREE.BufferGeometry. However, the texture displays correctly when using normal geometry. Could it be that textures are unsupported with BufferGeometry, or am I ...

Webpack bundling only a singular Typescript file rather than all of its dependencies

I'm currently facing a challenge while attempting to consolidate all the files in my Typescript project, along with their dependencies from node_modules, into a single file using Webpack. Despite trying multiple options, it seems that only the entry f ...

Application freezes when a pop-up window is launched

When using the tool, I encounter an issue where clicking a button triggers a modal window to appear. However, once the modal window pops up, my code stops executing until I manually close the new popup window. This interruption in the code prevents me fro ...

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...

Updating input values in AngularJS using a custom directive in AngularJS

When the value of an input does not meet a certain condition, I need to change it. In this example, if the unit price input is changed to a non-numeric value when adding a Detail, I want to set the value to "0.00". scope.$watch(attrs.ngModel, function(new ...

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

Refining an array with React's filter method

Currently, I am in the process of creating a To-Do Application using React. However, I have encountered a roadblock along the way. My struggle lies in mapping through items within an array and presenting them in an unordered list. I am attempting to util ...

Executing functions within express - a mystery

I am struggling with a back-end JavaScript issue in Express. For some reason, when I call my function, it is returning undefined. Here's how it looks: // express route structure: exports.check = function(req, res) { // check if the username is prese ...

What is the best way to divide my JavaScript objects among several files?

Currently, I'm in the process of organizing my JavaScript code into separate libraries. Within the net top-level-domain, I manage two companies - net.foxbomb and net.matogen. var net = { foxbomb : { 'MyObject' : function() { ...

Error: jquery unexpectedly encountered a token 'if'

I've successfully created an autocomplete suggestion box, but I'm facing an issue when using if and else along with console.log(). An error is displayed in my console saying Uncaught SyntaxError: Unexpected token if, and I'm not sure why. Ho ...

Adjust the button's background hue upon clicking (on a Wix platform)

I need some help with customizing the button "#button5" on my Wix website. Here are the conditions I'd like to apply: Button color should be white by default; When the user is on the "contact" page, the button color should change to red; Once the use ...

Jackson JSON throws an error stating that there is no appropriate constructor found for a type when an Enum is used

I have a class structured like this: public class Content { public enum Type { TEXT, URL, FILE } public enum Rendering { MARKDOWN, HTML, PLAIN, AUTO } public final Type type; pu ...

Is the append() function malfunctioning in jQuery?

Why is it copying two lines when I only want one line to be cloned on button click? Is there a way to make sure that only a single line is copied each time the button is clicked? Here is my code: $(function() { $('.add-more-room-btn').clic ...

Ways to generate a customized template using the directive attribute parameter

I have developed a new directive and I am looking to incorporate a dynamic template using the attribute wm.data.typeName. wm.data.typeName = "<span>html code</span>" <fill-choose model-input="wm.data.modelInput" text="wm.data.typeName"&g ...