When using Spring POST method, data is received with empty values in the

I am facing an issue with my AngularJS web application where it seems to be sending JSON correctly to the Tomcat server, but the server ends up receiving null values. I have looked at this question and this question for a solution, but they didn't help as expected. Edit: A comment pointed out that I misread the presence of the @RequestBody notation.

Here is the relevant server method:

@PostMapping(path="/kind/add")
public @ResponseBody String addNewKind(Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    kindRepository.save(kind);
    return "Saved";
}

Here is the structure of the Kind object being sent:

@Entity
public class Kind {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy="kind")
    private Set<Card> cards;

    // Getters and setters omitted for brevity
}

This is the request function in my code:

var uri = 'http://localhost:8080/catalog/api/kind/';

function create(name) {
    var deferred = $q.defer();
    var data = {
        'name': name
    };
    $http({
        method: 'POST',
        url: uri + 'add',
        data: angular.toJson(data),
        headers: {
            'Content-Type': 'application/json; charset=UTF-8'
        }
    }).then(function(response) {
        deferred.resolve(response.data);
    }).catch(function(error) {
        console.error('Error while adding kind');
        deferred.reject(error);
    });
    return deferred.promise;
}

This is the JSON payload being sent to the server:

{"name":"Something"}

N.B. Sending additional parameters like `id` or `cards` also results in the same problem, despite them being optional:

{"id":0,"name":"Something","cards":[]}

The request headers look like this:

Accept:           application/json, text/plain, */*
Accept-Encoding:  gzip, deflate
Connection:       keep-alive
Content-Length:   20
Content-Type:     application/json; charset=UTF-8
Host:             localhost:8080
User-Agent:       Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/57.0
// Other headers truncated for clarity

Upon debugging, the server receives the following values for the `kind` object:

kind= Kind
    cards= null
    id= 0
    name= null

Answer №1

Ensure that you include the @RequestBody annotation in your method to properly bind the posted object to your controller's Kind parameter.

@PostMapping(path="/kind/add")
public String addNewKind(@RequestBody Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    kindRepository.save(kind);
    return "Saved";
}

If you expect the new 'Kind' to be returned, adjust your controller method like this:

@PostMapping(path="/kind/add")
public Kind addNewKind(@RequestBody Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    return kindRepository.save(kind);
}

Also, take note of your JSON formatting - avoid using single quotes as JSON syntax requires double quotes for proper structure. If you are using Angular's angular.toJson() function, it should handle this correctly.

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 is the optimal method for leveraging Symfony2 to deliver AngularJS partials?

How should I serve partials from Symfony to Angular without using Twig? I'm considering setting up a route in Symfony and having the controller output the file, but I'm not sure how to do this without rendering through Twig. Will this method cac ...

Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to functi ...

The issue at hand is why the closure is not functioning properly when variables are assigned to the callback of the getCurrentLocation function

Apologies for the extensive amount of code, but it seems like there may be an issue with AppMobi's getCurrentLocation function in this scenario. The problem arises when tapping on list elements triggers an asynchronous getCurrentLocation call which up ...

In Java, establish an array only if it hasn't been created yet

I was unable to find any information on that topic while searching online, so I am looking to create an array only if it does not already exist. EDIT: By "not initialized" I mean... I am aware of how to check for values in the array. This should be a si ...

The process of setting up the syntax token for tags

Currently, I am using sails.js with ejs templating and successfully switched to nunjucks without any issues. However, I have discovered that the tags used in nunjucks are the same as those in angularjs and I would like to modify them. For more informatio ...

Can I use a single component for all routes in NextJS?

Just starting out with NextJS and facing a simple problem: I'm wondering if it's possible to achieve the following setup using NextJS // with react-router-dom <Router> <> <Header /> <Switch> & ...

Modify the menu class dynamically when scrolling using Angular and Bootstrap

I am a beginner in Angular and I am attempting to toggle between two Bootstrap menu classes when the page is scrolled. My goal is to keep the menu fixed at the top with a different background color (as defined in Bootstrap CSS) when the scroll is not at th ...

Recognize when the DOM undergoes modifications

After taking Matt's suggestion, I have made changes to the .ready() call. In my workflow, I utilize jQuery to set up certain configurations like this: $(function () { $('.myThing').each(function() { ... configuring happens he ...

The method base() in Java generics is not defined for type T

I'm diving into the concept of generics in Java and attempting to work on a simple example. However, I'm facing an issue where it keeps coming back with an error message: Exception in thread "main" java.lang.Error: Unresolved compilation probl ...

Stop the execution of javascript code based on the screen width

On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially ...

Activating style.display based on the date

Hello everyone! I'm new here so please bear with me if I make any mistakes. Can someone take a look and tell me what I'm doing wrong? I've created divs named "1st", "2nd", "3rd," etc., with the intention of setting up an advent calendar lay ...

Update the specific component according to the identified modifications

In my project, I have two simple components: parent and child. The parent component contains an Array and for each element in the array, it renders the child component. parent.component.ts export class parent implements OnInit { data: CustomType[] = [ ...

Using JavaScript within Razor C#

I am attempting to invoke a JavaScript function from within a helper method in Razor. Here is a snippet of my code: @helper MyMethod() { for (int i = 0; i < 5; i++) { drawMe(i) } } The drawMe function is defined in an externa ...

Angular: Creating a Sliding Menu with a Hamburger Icon

I have been attempting to implement a slide out menu from a span within my navigation bar, but I am encountering some challenges. Despite searching on Google, I have not been able to find the solution I need. Here is the code I am currently using: <div ...

When the click event is triggered on the modal, the page suddenly jumps to the top while applying the style of hiding the element

After implementing a modal that appears upon clicking an element on my webpage, I encountered an issue when trying to close it. I added an event listener to the 'close' link element in the top right corner of the modal with the following code sni ...

Converting from Async.js parallel to Bluebird: A Step-by-Step Guide

Utilizing async.js allows me to define promises with handlers, providing polymorphism and separating results. Can this be achieved in bluebird as well? async.parallel({ cityPromises: (cb)=>{ City.find({ ...

What is preventing me from loading a JavaScript script using a regular working URL?

After inserting the following line into my HTML file: <script type="text/javascript" src="http://static.citygridmedia.com/ads/scripts/v2/loader.js"></script> (whether inside or outside the <head></head> tags), I am encountering a ...

Is it possible to make jQuery dialog text behave like a JavaScript prompt?

Hello there, I have a query! I'm looking to allow users to easily copy text within a dialog window by simply pressing CTRL + C. Is this possible, and if so, how can it be achieved? An instance of this functionality is seen in the javascript alert pr ...

Error: The function _this[("render" + data.type)] is not defined as a valid function

https://i.stack.imgur.com/Y5Dz5.jpg I encountered an error in the console that I can't seem to figure out. Despite following the Syncfusion library's documentation, the error persists. Here is the code snippet that I implemented: import React f ...

Parsing CSV files in Java can be done by splitting the data into arrays based on

Can anyone help me with this task? I have a CSV file that looks like this: column1$column2$column3 123$xyz$321 456$zyx$654 I need to parse it in Java into arrays or array lists based on columns/headers. For example: ArrayList column1 = [ ...