1. Respond to JSON data through the SpringMVC framework

In the SpringMVC framework (including the SpringBoot framework), when @responseBody is added to the method that processes the request, or @RestController is used before the controller class, the return value of the method that processes the request is sent to the client as the response data.

When the server responds to data to the client, SpringMVC framework uses a “Converter” to convert the return value of the method and process the Response Headers. The SpringMVC framework also automatically uses different converters.

When the type of the response data (the return value of the method of dealing with the request type) is a String, will automatically be used StringHttpMessageConverter converter, the converter will automatically returns the String as a response to the client data, and will also set the response headers, by default, The content-Type attribute is set in the response header, with a value of text/ HTML; Charset =ISO-8859-1, so, in the SpringMVC framework (excluding the SpringBoot framework), by default, the response String does not support Chinese!

When the response data is of a type not recognized by the SpringMVC framework by default, and jackson-Databind dependencies are added to the current development environment, the SpringMVC framework automatically uses the converters in Jackson-Databind. The converters in Jackson-Databind work by organizing the response results into JSON-formatted data and setting the content-Type in the response header to Application/JSON. Charset = utf-8!

Just make sure you add jackson-Databind dependencies in your project, no extra configuration is required, and no explicit use of a class in the framework is required!

If you are a SpringMVC project that uses XML for configuration, you need to enable annotation-driven in the Spring configuration file.

<annotation-driven />
Copy the code

In general, if you want the SpringMVC framework to be able to respond to jSON-formatted data, you need to:

  • use@RestControlleror@ResponseBodyAnnotations;
  • Add in the projectjackson-databindRely on;
  • The return value type of the custom method that handles the request (as long as it is a custom type, the SpringMVC framework does not recognize any other type by default)

Of course, a controller class that already uses the @restController annotation will say “all requests processed in the current controller class will respond to data” will not perform a forward or redirect operation. If you must perform a forward or redirect, you can:

  • Do not use@RestControllerAnnotations are added one at a time before each method that requires response data@ResponseBodyAnnotations;
  • In the use of@RestControllerDeclare the return value type of the method to be forwarded or redirected asModelAndViewType.