@ RequestBody, @ ResponseBody annotation is how to convert the input and output of json

@ RequestBody, @ ResponseBody notes, can be directly input parsed into Json, the output parsed into Json, but HTTP requests and responses are text-based, meaning that the browser and server communicate by exchanging the original text, but this is actually play HttpMessageConverter a role.

HttpMessageConverter

Http request response packet string fact, when the request packet to the java application may be packaged as a stream ServletInputStream, developers then read packet, response packet through ServletOutputStream stream, and outputs the response packet.

Only read from the stream to the original message string, it is the same output stream. Then the packet reaches SpringMVC / SpringBoot and from SpringMVC / SpringBoot out, there is a problem converting a string to java object. This process, in SpringMVC / SpringBoot in, is solved by HttpMessageConverter. HttpMessageConverter Interface Source:

public interface HttpMessageConverter<T> { boolean canRead(Class<?> clazz, MediaType mediaType); boolean canWrite(Class<?> clazz, MediaType mediaType); List<MediaType> getSupportedMediaTypes(); T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException; void write(T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException; } 

Below an example to illustrate:

@RequestMapping("/test")
@ResponseBody
public String test(@RequestBody String param) { return "param '" + param + "'"; } 

Before entering the test method of the request, will select the corresponding annotated according @RequestBody HttpMessageConverter implementation class to resolve the request parameter param tag because the arguments are of type String, so here is the use of StringHttpMessageConverter class, it canRead () the method returns true, then the read () method will read the request from the request parameter, variable param bound to test () method.

Similarly when performing the test method, since the return value identifies @ ResponseBody, SpringMVC / SpringBoot StringHttpMessageConverter using the write () method, the result value is written as a String response message, of course, at this time returns true canWrite () method.

FIG borrow the brief description of the process:

 

 
00001.png

 

Spring in the process, the first request packet and a response packet are abstracted as a request message and a response message HttpInputMessage HttpOutputMessage.

When the processing request from the appropriate converter request message packet bound for the parameter in the subject methods, where there are many different message may appear in the form of the same object, such as json, xml. Also in response to the request it is the same reason.

In Spring, for different message forms, there are different classes of HttpMessageConverter implemented to handle various message forms, as implemented in a variety of different message parsing is achieved in a different class HttpMessageConverter.

Replace @ResponseBody default HttpMessageConverter

As used herein SpringBoot demo examples, used by default in SpringMVC / SpringBoot in @RequestBody such annotations are jackson to parse json, look at the following example:

@Controller
@RequestMapping("/user") public class UserController { @RequestMapping("/testt") @ResponseBody public User testt() { User user = new User("name", 18); return user; } } 
public class User {

    private String username; private Integer age; private Integer phone; private String email; public User(String username, Integer age) { super(); this.username = username; this.age = age; } } 

Browser access / user / testt returns the following:

 

 
00002.png

 

This is the use of analytical results jackson, now changed to use fastjson be analyzed, here is replace the default HttpMessageConverter, is to change it to use FastJsonHttpMessageConverter to handle conversion between Java objects and HttpInputMessage / HttpOutputMessage.

First create a configuration class to add a configuration FastJsonHttpMessageConverter, Spring4.x began to recommend the use of the Java configuration annotated manner, that is, no xml file, SpringBoot even more of.

import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import java.nio.charset.Charset; @Configuration public class HttpMessageConverterConfig { //引入Fastjson解析json,不使用默认的jackson //必须在pom.xml引入fastjson的jar包,并且版必须大于1.2.10 @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { //1、定义一个convert转换消息的对象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、添加fastjson的配置信息 FastJsonConfig fastJsonConfig = new FastJsonConfig(); SerializerFeature[] serializerFeatures = new SerializerFeature[]{ // 输出key是包含双引号 // SerializerFeature.QuoteFieldNames, // 是否输出为null的字段,若为null 则显示该字段 // SerializerFeature.WriteMapNullValue, // 数值字段如果为null,则输出为0 SerializerFeature.WriteNullNumberAsZero, // List字段如果为null,输出为[],而非null SerializerFeature.WriteNullListAsEmpty, // 字符类型字段如果为null,输出为"",而非null SerializerFeature.WriteNullStringAsEmpty, // Boolean字段如果为null,输出为false,而非null SerializerFeature.WriteNullBooleanAsFalse, // Date的日期转换器 SerializerFeature.WriteDateUseDateFormat, // 循环引用 SerializerFeature.DisableCircularReferenceDetect, }; fastJsonConfig.setSerializerFeatures(serializerFeatures); fastJsonConfig.setCharset(Charset.forName("UTF-8")); //3、在convert中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); //4、将convert添加到converters中 HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } } 

Here, if the value is null string type return, "" and the value type of null is returned if it is 0, restart the application, access / user / testt interfaces again, returns the following:

 

 
00003.png

 

Can be seen at this time is converted into null "" or a 0.

Guess you like

Origin www.cnblogs.com/HHR-SUN/p/11639801.html