Home  >  Article  >  Java  >  How to Bidirectionally Transfer JSON Data with Spring MVC and jQuery?

How to Bidirectionally Transfer JSON Data with Spring MVC and jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 00:44:18935browse

How to Bidirectionally Transfer JSON Data with Spring MVC and jQuery?

Tackling Bidirectional Data Transfer with JQuery, Spring MVC, and JSON

Despite the success in achieving Java to JSON data transfer using @ResponseBody, implementing its reverse path has been elusive. This article delves into the solution to serialize JSON back into a Java object using @RequestBody.

Prerequisites for Success

To ensure a seamless experience, ensure the following:

  • Proper Jackson Configuration: Verify that MappingJacksonHttpMessageConverter is registered, usually achieved through in XML or @EnableWebMvc in Java.

A Comprehensive Example

To illustrate the solution, consider the example below:

web.xml:

<servlet>
  <servlet-name>json</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>json</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

json-servlet.xml:

<beans>
  <import resource="classpath:mvc-context.xml" />
</beans>

mvc-context.xml:

<beans>
  <mvc:annotation-driven />
  <context:component-scan base-package="test.json" />
</beans>

TestController (controller class):

@Controller
@RequestMapping("/test")
public class TestController {

  @RequestMapping(method = RequestMethod.POST, value = "math")
  @ResponseBody
  public Result math(@RequestBody final Request request) {
    ...
  }

}

Request (POJO for POST requests):

public class Request {
  private int left;
  private int right;
  ...
}

Result (POJO for serialized responses):

public class Result {
  private int addition;
  private int subtraction;
  private int multiplication;
  ...
}

Testing the Solution

Execute the command mvn jetty:run and send the following POST request:

  • URL: http://localhost:8080/test/math
  • MIME Type: application/json
  • Post Body: { "left": 13, "right" : 7 }

The response you should receive:

{"addition":20,"subtraction":6,"multiplication":91}

This demonstrates the bidirectional data transfer between JSON and Java using @RequestBody.

The above is the detailed content of How to Bidirectionally Transfer JSON Data with Spring MVC and jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn