Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with the message converter after modifying the return value type in SpringMVC

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report