例子:
导入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
person和pet存在级联关系的javabean
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
public class Person {
private String name;
private Integer age;
private Date birth;
private Pet pet;
}
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Pet implements Serializable {
private String name;
private Integer age;
}
html页面,使用thymeleaf模板引擎
<form method="post" th:action="@{/savePerson}">
姓名:<input type="text" name="userName" value="zhangsan"><br>
年龄:<input type="text" name="age" value="18"><br>
生日:<input type="text" name="birth" value="2019/12/10"><br>
<!-- 宠物姓名:<input type="text" name="pet.name" value="阿猫"><br>-->
<!-- 宠物年龄:<input type="text" name="pet.age" value="5"><br>-->
宠物:<input type="text" name="pet" value="阿猫,3"><br>
<button type="submit" >保存</button>
</form>
配置类:WebMvcConfigurer
@Configuration(proxyBeanMethods = false)//放的组件没有依赖 用false快速
public class WebConfig /*implements WebMvcConfigurer*/ {
/*
第②种:开启矩阵变量功能
WebMvcConfigurer定制化SpringMVC的功能
*/
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<String, Pet>() {
@Override
public Pet convert(String source) {
//阿猫,3
if(!StringUtils.isEmpty(source)){
Pet pet = new Pet();
String[] split = source.split(",");
pet.setName(split[0]);
pet.setAge(Integer.parseInt(split[1]));
return pet;
}
return null;
}
});
}
};
}
}
controller层
@ResponseBody
@PostMapping("/savePerson")
public Person savePerson(Person person){
return person;
}
测试: