文章目录
- 前言
- 一、请求对象
- 二、自定义转换器
- 三、注册转换器
- 四、控制器
- 五、执行顺序
- 六、执行结果
- 总结
前言
【第6章】spring类型转换器
在spring系列已经介绍了类型转换器、接下来我们通过案例了解下转换器在SpringMvc中的应用。
场景模拟:我们接收到客户端请求,解析请求字符串及进一步解析请求体,返回Request请求对象。
一、请求对象
package org.example.springmvc.converters.custom;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Create by zjg on 2024/5/1
*/
@Getter
@Setter
@ToString
public class Request {
private String id;//流水号
private String headers;//请求头
private String body;//请求体
private String timestamp;//时间戳
private String salt;//盐值
}
二、自定义转换器
package org.example.springmvc.converters.custom;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.util.Base64;
/**
* Create by zjg on 2024/5/1
*/
public class RequestConverter implements Converter<String,Request> {
@Override
public Request convert(String source) {
Request request = JSONObject.parseObject(source, Request.class);
if(!StringUtils.hasText(request.getId())){
throw new IllegalArgumentException("请求流水号不能为空!");
}
request.setBody(new String(Base64.getDecoder().decode(request.getBody())));
return request;
}
}
三、注册转换器
package org.example.springmvc.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Create by zjg on 2024/4/27
*/
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new RequestConverter());
WebMvcConfigurer.super.addFormatters(registry);
}
}
四、控制器
package org.example.springmvc.converters;
import com.alibaba.fastjson2.JSONObject;
import org.example.springmvc.converters.custom.Request;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Create by zjg on 2024/5/1
*/
@RestController
public class ConverterController {
@RequestMapping("/getRequest")
public String getRequest(){
Request request=new Request();
request.setId("B490B5EBF6F3CD402E515D22BCDA1598");
request.setHeaders("");
request.setBody("5a+55oiR5p2l6K+077yM5YGa6I+c5YGa6Z2i5YyF5piv5LiA56eN5aix5LmQ5pa55byP77yM5piv5omT5Y+R5pe26Ze055qE5pyJ5pWI5omL5q6177yM5piO55m95ZCX77yf");
request.setTimestamp("1714573836828");
request.setSalt("123456");
return JSONObject.toJSONString(request);
}
@RequestMapping("/request")
public Request request(Request request){
System.out.println(request);
return request;
}
}
五、执行顺序
localhost:8080/getRequest
localhost:8080/request
六、执行结果
Request(id=B490B5EBF6F3CD402E515D22BCDA1598, headers=, body=对我来说,做菜做面包是一种娱乐方式,是打发时间的有效手段,明白吗?, timestamp=1714573836828, salt=123456)
总结
回到顶部
官方文档
postman测试脚本已上传,下载导入即可用。