SpringBoot2.0自定义从页面映射出来的数据类型Convert的自定义
根据我们页面传过来的类型定义,我们的类型转换,比如这里,
宠物:<input name="pet" value="啊狗,3">,
如何自定义成我需要的类型,configurePathMatch是手动开启矩阵,不用管。
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
//不移除,后面的内容,矩阵变量功能就可以生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
//自定义Convert转换
@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(split[1]);
return pet;
}
return null;
}
});
}
};
}
}
本文介绍了如何在SpringBoot 2.0中自定义页面上传宠物信息(如'啊狗,3')到Pet对象的转换逻辑,通过`WebMvcConfigurer`实现字符串到自定义Pet类的转换。
933

被折叠的 条评论
为什么被折叠?



