HttpMessageConverter如果不指定Accept和Content-Type,那么HttpMessageConverter按顺序调用canRead方法判断(默认canRead方法中分别调用supports和重载的canRead方法,其中supports方法由子类实现,canRead方法根据MediaType判断,如果为null则返回true。但Jackson转换器重写了canRead方法)
自定义HttpMessageConverter
- 实现请求参数为properties数据结构,返回json数据结构
1、创建自定义HttpMessageConverter
package com.cnbi.sourceread.mvc.converter;
import com.cnbi.sourceread.bean.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Properties;
/**
* @ClassName MappingPropertiesHttpMessageConverter
* @Description Properties参数转换
* @Author Wangjunkai
* @Date 2021/2/20 23:28
**/
public class MappingPropertiesHttpMessageConverter extends AbstractHttpMessageConverter {
public MappingPropertiesHttpMessageConverter(){
super(Charset.forName("UTF-8"), MediaType.valueOf("application/properties"));
}
@Override
protected boolean supports(Class clazz) {
return clazz.isAssignableFrom(Person.class);
}
@Override
protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
InputStream body = inputMessage.getBody();
Properties properties = new Properties();
properties.load(body);
return new Person(Long.parseLong(properties.getProperty("person.age")), properties.getProperty("person.name"));
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
Properties properties = new Properties();
if(o instanceof Person){
Person person = (Person) o;
properties.setProperty("person.age", String.valueOf(person.getAge()));
properties.setProperty("person.name", person.getName());
}
properties.store(outputMessage.getBody(), "write by server");
}
}
2、添加MappingPropertiesHttpMessageConverter
package com.cnbi.sourceread.mvc.converter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
/**
* @ClassName ConsumerMvcConfiger
* @Description 自定义MVC配置
* @Author Wangjunkai
* @Date 2021/2/20 23:39
**/
@Configuration
public class ConsumerMvcConfiger extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingPropertiesHttpMessageConverter());
addDefaultHttpMessageConverters(converters);
}
}
博主个人微信