import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CommonConfig implements WebMvcConfigurer {
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<String, String[]>() {
@Override
public String[] convert(String source) {
String[] strings = null;
if (source != null) {
strings = new String[] { source };
}
return strings;
}
});
registry.addConverter(new Converter<String[], String>() {
@Override
public String convert(String[] values) {
String str = null;
if (values != null) {
str = values.length > 0 ? values[0] : null;
}
return str;
}
});
registry.addConverter(new Converter<Object[], Object>() {
@Override
public Object convert(Object[] values) {
Object str = null;
if(isNum((String) (values)[0])) {
str = ((Object[]) values)[0];
}else {
str = "0";
}
return str;
}
});
}
private boolean isNum(String str) {
try {
Long.parseLong(str);
} catch (Exception e) {
return false;
}
return true;
}
}
FormatterRegistry配置应用的格式转换功能
最新推荐文章于 2025-11-18 14:25:08 发布
本文介绍了如何在SpringMVC的WebMvcConfigurer中,通过自定义Converter实现String、String[]和Object[]之间的转换,重点是处理数字类型的特殊处理。
3830

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



