In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about Spring MVC how to modify the way message converters handle return value types. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
problem case
Suppose there is a Controller method as follows
@RequestMapping(value = "test") @ResponseBody public Object test() { Map param = new HashMap(); param.put("name","userwyh"); return param; }
Then we modify the return value before outputting it by implementing the ResponseBodyAdvice interface, where we change it to a String type and return hello,world directly.
@ControllerAdvicepublic class MyResponseBodyAdvice implements ResponseBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Class> aClass) { return true; } @Override public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { return "hello,world"; }}
This way, no matter what value the test method in Controller returns, we'll turn it into hello, world output. There is nothing wrong with thinking about it, carefully confirming the code, and it does just that.
So, start the project, open the browser, enter localhost:8080/test in the address bar, and enter.
We did see hello,world, and there was no problem.
But if you take a closer look, you'll notice that hello,world has an extra quote around it. This is obviously not the return value we want!!
Why not?
At this point, the Spring MVC message converter HttpMessage Converter mentioned in the title should appear.
HttpMessageConverter source code analysis can be moved to SpringMVC source code analysis-message converter HttpMessageConverter view. We do not have a detailed interpretation of the source code here.
First SpringMVC loads the message converters configured in spring-servlet.xml into messageConverters.
protected final List
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.