栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC-返回值处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC-返回值处理

一、介绍

(1)找到对应的返回值处理器,如方法标注了@ResponseBody,则使用ResponseBody返回值处理器。
(2)ResponseBody返回值处理器先判断是否是流式数据,再进行内容协商。
(3)内容协商先找到对应的内容协商管理器,如参数内容协商策略、请求头内容协商策略,利用上述内容协商策略获取浏览器支持的内容类型。
(4)找到能处理该返回值的消息转换器并记录其支持的内容类型,然后根据内容类型权重找到消息转换器处理返回值。

二、参数内容协商策略

(1)开启默认的参数内容协商策略

spring.mvc.contentnegotiation.favor-parameter=true

(2)自定义内容协商策略

@Configuration(proxyBeanMethods = false)
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        Map mp = new HashMap();
        mp.put("wsh", MediaType.parseMediaType("application/json"));
        ParameterContentNegotiationStrategy pcs = new ParameterContentNegotiationStrategy(mp);
        configurer.strategies(Arrays.asList(pcs));
    }
}

三、自定义消息转换器(可用在@ResponseBody和@RequestBody)

(1)编写配置类

@Configuration(proxyBeanMethods = false)
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List> converters) {
        converters.add(new HttpMessageConverter() {

            @Override
            public boolean canRead(Class aClass, MediaType mediaType) {
                return false;
            }

            @Override
            public boolean canWrite(Class aClass, MediaType mediaType) {
                return aClass.isAssignableFrom(Person.class);
            }

            @Override
            public List getSupportedMediaTypes() {
                return MediaType.parseMediaTypes("application/wsh");
            }

            @Override
            public Person read(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
                return null;
            }

            @Override
            public void write(Person person, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
                OutputStream body = httpOutputMessage.getBody();
                body.write((person.getName() + " " + person.getAge()).getBytes());
                body.flush();
            }
        });
    }
}

(2)编写Controller

@Controller
public class HelloController {

    @GetMapping("/user")
    @ResponseBody
    public Person getUser(){
        Person person = new Person("wsh", 20);
        return person;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号