1.简介
1.1 概述
Spring MVC uses the
HttpMessageConverter
interface to convert HTTP requests and responses. Sensible defaults are included out of the box. For example, objects can be automatically converted to JSON (by using the Jackson library) or XML (by using the Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not available). By default, strings are encoded inUTF-8
.
Spring MVC使用HttpMessageConverter接口转换HTTP请求和响应。开箱即用中包含明智的默认设置。例如,可以将对象自动转换为JSON(通过使用Jackson库)或XML(通过使用Jackson XML扩展(如果可用)或通过使用JAXB(如果Jackson XML扩展不可用))。默认情况下,字符串以UTF-8编码。
1.2 特点
HttpMessageConverter 是一个接口,它包含以下几个方法
- canRead: 判断是否支持解析当前 MediaType
- canWrite: 判断是否支持输出当前 MediaType
- getSupportedMediaTypes: 获取支持的 MediaTypes
- read: 解析http消息内容
- write: 输出指定MediaType的消息内容
这里的MediaType即为http请求中常见的 Content-Type;例如:application/json、application/xml等
2.演示环境
- JDK 1.8.0_201
- Spring Boot 2.2.0.RELEASE
- 构建工具(apache maven 3.6.3)
- 开发工具(IntelliJ IDEA )
3.演示代码
3.1 代码说明
自定义HttpMessageConverter消息转换器,实现消息的解析和输出
3.2 代码结构
3.3 maven 依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3.4 配置文件
无配置
3.5 java代码
UserModel.java
public class UserModel {
private Long id;
private String name;
private Integer age;
private Date birthday;
private BigDecimal salary;
private String phone;
public UserModel() {
}
public UserModel(Long id, String name, Integer age, Date birthday, BigDecimal salary, String phone) {
this.id = id;
this.name = name;
this.age = age;
this.birthday = birthday;
this.salary = salary;
this.phone = phone;
}
// get&set&toString
}
UserRepository.java
@Repository
public class UserRepository {
private static final AtomicLong ID_GENERATOR = new AtomicLong(2);
private static final Map<Long, UserModel> USER_MAP = new HashMap<>();
@PostConstruct
public void init() {
UserModel user1 =
new UserModel(1L, "zhangsan", 20, new Date(), new BigDecimal("23456.11"), "13666666666");
UserModel user2 =
new UserModel(2L, "lisi", 30, new Date(), new BigDecimal("12345.67"), "13888888888");
USER_MAP.put(user1.getId(), user1);
USER_MAP.put(user2.getId(), user2);
}
public List<UserModel> findAll() {
return new ArrayList<>(USER_MAP.values());
}
public UserModel findById(Long id) {
return USER_MAP.get(id);
}
public UserModel add(UserModel userModel) {
long id = ID_GENERATOR.incrementAndGet();
userModel.setId(id);
USER_MAP.put(id, userModel);
return userModel;
}
public UserModel update(UserModel userModel) {
USER_MAP.put(userModel.getId(), userModel);
return USER_MAP.get(userModel.getId());
}
public UserModel deleteById(Long id) {
UserModel userModel = USER_MAP.get(id);
USER_MAP.remove(id)