自定义请求数据转换器convert
配置类
@Component public class MyConfig { @Bean public WebMvcConfigurer webMvcConfigurer(){ return new WebMvcConfigurer() { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new Converter<String, User>() { @Override public User convert(String source) { if(StringUtils.hasText(source)){ User user = new User();
// 页面请求中英文都好连接 String[] strings = source.split(","); user.setName(strings[0]); user.setAge(Integer.parseInt(strings[1])); return user; } return null; } }); } }; } }
Controller
@ResponseBody @PostMapping("/saveInfo") public Map<String,Object> saveInfo(Info info){ Map<String,Object> map = new HashMap<>(); map.put("info",info); return map; }
实体
@Data @ToString public class Info { private String userId; private String address; private String birth; private User user; }
@Data @ToString public class User { private String name; private int age; }
页面请求
<form action="/saveInfo" method="post"> 编号: <input name="userId" value="9587"/> <br/> 年龄: <input name="address" value="长春"/> <br/> 生日: <input name="birth" value="2022/7/15"/> <br/> 姓名年龄: <input name="user" value="张三,1"/> <input type="submit" value="保存"/> </form>
结果输出
请求处理-源码分析