The JSON request triggers an unsupported media error in the Spring MVC controller

I'm having trouble sending a JSON object to the server. I've tried various solutions from StackOverflow, but none of them seem to work:

On the client side:

function submitWOZ(){
var sub = {
     "idNextexercise": parseInt($('#exList').val()), 
     "user": $('#user').val()   
    };
$.ajax({
    type: 'POST',
    headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' 
    },
    dataType : 'json',
    url: "insertNextID",
    //data: JSON.stringfy(sub),
    data: sub,
    success: function(data){
        alert('Great!');
    },
    error : function(jqXHR, status, error) {
       alert('Sorry!, something went wrong');
    },
    complete : function(jqXHR, status) {
       alert('Done!');
    }
});

}

On the server side:

@RequestMapping(value = "/insertNextID", method = RequestMethod.POST, consumes = {"application/xml", "application/json"})
public @ResponseBody String insertNextExercise(@RequestBody ExerciseVO messageForm, HttpServletRequest req){}

In my Context-config:

<mvc:annotation-driven/>

<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/" />
<mvc:default-servlet-handler />

<!-- Thymeleaf template resolver -->
<bean id="templateResolver"
      class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    <property name="prefix" value="/WEB-INF/" />
    <property name="templateMode" value="HTML5" />
</bean>

<!-- Thymeleaf Template Engine -->
<bean id="templateEngine"
      class="org.thymeleaf.spring3.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />
    <property name="additionalDialects">
        <set>
            <bean class="org.thymeleaf.extras.tiles2.dialect.TilesDialect"/>
            <bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect"/>
            <bean class="org.thymeleaf.extras.conditionalcomments.dialect.ConditionalCommentsDialect"/>
        </set>
    </property>
</bean>

<!-- Resolves logical view names returned by Controllers to Tiles; a view name to resolve is treated as the name of a tiles definition -->
<bean id="tilesViewResolver" class="org.thymeleaf.spring3.view.AjaxThymeleafViewResolver">
    <property name="viewClass" value="org.thymeleaf.extras.tiles2.spring.web.view.FlowAjaxThymeleafTilesView"/>
    <property name="templateEngine" ref="templateEngine"/>
</bean>

<!-- Configures the Tiles layout system using a specific thymeleaf-enabled Tiles Configurer -->
<bean id="tilesConfigurer" class="org.thymeleaf.extras.tiles2.spring.web.configurer.ThymeleafTilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/**/views.xml</value>
        </list>
    </property>
</bean>

<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="prefixJson" value="false" />
    <property name="supportedMediaTypes" value="application/json" />
</bean>

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json" />
        </map>
    </property>

    <property name="defaultViews">
        <list>
            <bean
                class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                <property name="objectMapper">
                    <ref bean="JacksonObjectMapper" />
                </property>
            </bean>
        </list>
    </property>
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="useNotAcceptableStatusCode" value="true" />
</bean>

<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

Can anyone assist me? I've exhausted all the solutions I found online.

Answer №1

To troubleshoot the issue, you can introduce a new filter in the web.xml and examine whether the incoming request to the server matches your expectations. If everything seems fine, attempt to override the jsonHttpMessageConverter by including it in your context configuration file, and investigate why your call is being rejected. Multiple factors can contribute to this problem, so it's crucial to monitor your request's progress on the server side and identify where it gets stuck.

Answer №2

It seems that the issue may arise from the absence of JSON/XML parsers in the classpath, causing spring MVC to be unable to generate the requested content.

To enable the return of responses in JSON/XML format, it is essential to include a set of libraries in the classpath.

For instance, for JSON, we typically add the Jackson parser to the classpath using these specific components for version 2.1:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.1.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.1.3</version>
</dependency> 

The specific components required depend on the chosen parser and, in the case of Jackson, can also be influenced by the version. Older versions utilize different names for the artifacts.

Answer №3

  1. Temporarily removing the entire consumes parameter from the controller can help in troubleshooting.
  2. After reinstating the consumes parameter, try enhancing the $.AJAX call by adding contentType: "application/json" instead of including it in the headers section.

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

Create a dynamic webpage where two div elements glide in opposite directions

My apologies for this seemingly basic question, but I am wondering if anyone knows how to create an animation where a div moves up and down while scrolling, similar to the effect on this website: On that site, near the footer, there are 2 sections with 2 ...

The challenge with Normalizr library in Redux and how to address it

I am currently attempting to utilize the Normalizr library by Paul Armstrong in order to flatten the Redux state. Below are the schema definitions: import { normalize, schema } from 'normalizr' const fooSchema = new schema.Entity('foos&apo ...

Use JQuery to load a particular page by specifying its ID with the hashtag symbol

I am facing an issue where I need to create multiple private chatrooms per user. Although I have managed to make it work, I encountered a problem where if there are more than one private chats happening simultaneously, the content of these chats gets broad ...

Database storage of image tags on websites, similar to functionality found on social media platforms such as Facebook

Looking for an image tagging solution for websites that can save tag data directly to a database instead of a local file? I've checked out , but it doesn't support database integration in the current version. Ideally, I need a solution that is co ...

Clicking on Google Code Prettify does not trigger syntax highlighting

I utilize Google Code Prettify for syntax highlighting my code. Below is the HTML snippet I use: <head> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> </head> <body> ...

Issue with Jquery Mobile: Listview not showing up as expected

I am currently utilizing Jquery mobile version 1.4.1. I have been attempting to display a jquery mobile list view, but it is not showing correctly when I insert the code using Jquery. The issue lies in the fact that the jquery script does not include the n ...

Converting a JSON string into a Dictionary<String, Integer> using Gson parser

I encountered a JSON string that appears like this: {"altruism":1,"amazon":6} My goal is to create a HashMap<String, Integer> with two entries based on this string. Key: altruism Value: 1 Key: amazon Value:6 I am struggling to find the solution fo ...

Creating identical height columns with uniform inner elements is a problem that needs to be solved with caution. The proposed solution

Issue: I need to create a responsive layout with 5 columns, each containing an image, title, and text. The goal is to align the images separately, titles together, and texts individually while ensuring that all elements in a row have the same height. Solu ...

Are Json.load operations considered inefficient?

While browsing through the json module's source code in search of an answer to another question, I stumbled upon something quite intriguing. After removing the docstring and various keyword arguments, the essence of json.load is revealed as follows: ...

Tips for creating a responsive JSON object with a dynamic property name determined by the value of the provided eventType

Query: baseUrl/eventType/Sales/ The request URL can have eventType values like Sales, Claims, Receiving. Depending on the eventType specified, the below id should be adjusted. "id": "123", "sales": [ { "weekStartDate": "10-01-2020", "qt ...

Tips for retrieving the value associated with a key in a jsonnode

My JsonNode data looks like this: "{"Pink":["#000000"],"Red":["#000000"],"Blue":["#000000"],"Orange":["#000000"]}" I am attempting to retrieve the value for Pink usi ...

Retrieving table names while querying database in Python Flask

Recently, I made the switch from PHP to Flask after three years. I successfully connected to my local server and database, and managed to query data from it and display it on screen. However, when attempting to work on a small REST API project, I ran int ...

Is it possible to access the CSS property from an external CSS file even when inline styles are used?

Is there a way to retrieve the css property from an external source using JavaScript or jQuery even if inline styles are applied to the same element? Here's an example: <div id="my" style='left:100px'>some content</div> <styl ...

Angular integration of Jquery UI datapicker with read-only feature

Having trouble using ngReadonly within a directive, my code isn't functioning as expected: app.directive('jqdatepicker', function() { return { restrict: 'A', require : 'ngModel', link : functi ...

Having difficulty sending ajax to the controller function

Currently, I am facing an issue with updating my database using AJAX in Laravel. The goal is to change the value in the enable column from 1 to 0 when a toggle button is clicked. Below script is included in the view: $(".toggle-btn").change(function() { ...

What is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

There is no data available in the ajax request

Having issues with an ajax request for incrementing/decrementing items in a shopping cart. The post array comes up empty when printed. In Firebug, the params are shown as being sent in the post request, but nothing arrives in the controller. The solution ...

I am facing an issue with properly linking my jQuery

After searching through numerous posts on this website, I have yet to find a solution to my problem. My issue involves trying to implement a simple jQuery function that is not functioning as expected. It appears that the jQuery link may not be properly set ...

Definition of JSON Schema attribute: Field schema not supported for field... : Type of field is undefined

I am in the process of creating a form that is based on a JSON schema and utilizing the react-jsonschema-form component for ReactJS. The purpose of this form is to allow users to input various settings (such as CSS/HTML selectors) that will be used to ext ...

Exploring the Input Items to Extract Minimum and Maximum Values

I am seeking assistance with implementing JQuery Min Max Validation for dynamically created input items in a looping structure. On my PHP page, I have a dynamic table that iterates through data fetched from the database. The number of input items (cells) i ...