JavaScript object conversion to Java Model is proving to be a challenge

When looking at my Spring controller and client-side Javascript code, I noticed that the Javascript object is having trouble reaching the Spring controller in Object form. Here is a snippet of my Controller code:

@RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(@ModelAttribute("employeeRating") EmployeeRating employeeRating) {  
    if(employeeRating.getId()==0)
    {
        employeeRatingService.addRating(employeeRating);
    }
    else
    {   
        employeeRatingService.updateRating(employeeRating);
    }

    return employeeRating;
}

And here is a glimpse of my Javascript code:

$.ajax({
          url: 'https://myrestURL/addRating',
          type: 'POST',
          dataType: 'json',
          data: {
              'id':5,
              'name': 'Name',
              'rating': '1'
          },
          contentType: 'application/json; charset=utf-8',
          success: function (result) {
             // CallBack(result);
             window.alert("Result: " + result);
          },
          error: function (error) {
              window.alert("Error: " + error);
          }
      });

The Java EmployeeRating object entails id, name, and rating fields which should align perfectly with the setup.


I decided to update the model class structure:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/* 
 * This represents our model class corresponding to the Country table in the database
 */
@Entity
@Table(name="EMPLOYEERATING")
public class EmployeeRating {

@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

@Column(name="name")
String name;    

@Column(name="rating")
long rating;

public EmployeeRating() {
    super();
}
public EmployeeRating(int i, String name,long rating) {
    super();
    this.id = i;
    this.name = name;
    this.rating=rating;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public long getRating() {
    return rating;
}
public void setRating(long rating) {
    this.rating = rating;
}   

}

Answer №1

contentType is used to specify the type of data being sent, such as application/json. The default value is set to

application/x-www-form-urlencoded; charset=UTF-8
.

When using application/json, you must utilize JSON.stringify() to send a JSON object.

JSON.stringify() converts a JavaScript object into a JSON text and stores it as a string.

$.ajax({
      url: 'https://myrestURL/addRating',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({
          'id':5,
          'name': 'Name',
          'rating': '1'
      }),
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
         // CallBack(result);
         window.alert("Result: " + result);
      },
      error: function (error) {
          window.alert("Error: " + error);
      }
  });

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

There seems to be an issue with the compatibility of the Action class in Selenium version 3.5

I am currently trying to implement drag and drop functionality on a webpage, using the action class in Selenium. Although my code runs without any errors, unfortunately I am not able to achieve the desired functionality. I have tested the code on both Fi ...

Tips for assigning unique non-changing keys to siblings in React components

I've been searching for a solution for more than an hour without success. The structure of the data is as follows: const arr = [ { id: 1, title: 'something', tags: ['first', 'second', 'third'] }, { id: 2, t ...

Methods to Exclude api_key from URL in AngularJS

To make a GET request to a REST API, I require an apikey. The request will be formed like this - $http.get() The response from the API will be in JSON format. However, for security reasons, I don't want the api key to be visible in the URL. Is ther ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

What is the process for accessing the theme spacing unit in MUI 5?

In previous iterations of MUI, accessing the theme spacing unit was possible through theme.spacing.unit, with a default output of 8. However, this property has been removed in MUI 5. I am having trouble finding documentation on how to access the theme sp ...

The event listener for jQuery's document.ready doesn't trigger, rendering all jQuery functions ineffective

After researching similar issues on various forums, I have attempted the following troubleshooting steps: replacing all $ with jQuery ensuring the correct src is used implementing jQuery.noConflict() My goal is to retrieve data from a SQLite3 database w ...

Finding the specific ajax object that has been returned

Here is the code snippet I am currently working with: $.ajax({ type: 'POST', url: rAction, data: rData, success: function(msg){ if(msg.indexOf('ERROR:')>1){ } if(msg.indexOf('ERROR:&ap ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

Issue with Material UI scrollable tabs failing to render properly in Internet Explorer

Currently, we are integrating Material UI into our tab control for our React Web UI. Everything is functioning smoothly in Chrome, but when we attempted to test it in IE, the page failed to load and presented the error below: Unhandled promise rejection ...

Challenges encountered during the execution of React tests: Enzyme, Jest, and React integration

Encountered an error while running tests: FAIL src/components/common/user/UserMenu/__tests__/UserMenu.test.js ● Runtime Error Error: Failed to get mock metadata: /redacted-directory/node_modules/core-js/library/modules/_global.js See: http://facebook ...

``There seems to be an issue with implementing the SlideDown feature in JavaScript

I am having an issue with a code where the expected behavior is to slide down a div when a person hovers over text, but it's not working. Can someone please review and identify the cause of this problem? <script type="text/javascript" src="/js/jqu ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

Parsing precise decimal values from JSON file using Java

I have a JSON document structured like this. { "name": "Smith", "Weight": 42.000, "Height": 160.050 } To process this file, I've created the following Java code. import org.json.simple.JSONOb ...

What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX. I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered. 1) It appears that the Javascript function proce ...

The statement ... is not a valid function, it has returned undefined

Currently experimenting with AngularJS, encountered an error message: Argument 'Controller' is not a function, got undefined View the JSFiddle link, along with HTML code: <h2>Hata's Tree-Like Set</h2> <div ng-app ng-init="N=3 ...

Error message displayed in jQuery dialog box

My dilemma arises when attempting to continuously call a dialog box for displaying and submitting an enquiry form on my website. Upon the first submission, everything seamlessly goes through. However, clicking the GO button (as shown in the HTML below) tri ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...