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<String, MediaType> 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<HttpMessageConverter<?>> converters) {
        converters.add(new HttpMessageConverter<Person>() {

            @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<MediaType> getSupportedMediaTypes() {
                return MediaType.parseMediaTypes("application/wsh");
            }

            @Override
            public Person read(Class<? extends Person> 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;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值