自定义Spring转换器解决参数格式转换异常

自定义Spring转换器解决参数格式转换异常

lixiangrong
2024-01-03 / 0 评论 / 6 阅读 / 正在检测是否收录...

自定义Spring转换器解决参数格式转换异常

1.出现的场景

当某个实体查询参数类型是Long,Integer,BigDecimal等的时候,前端按照规范如果没有参数应该不传递参数,但是却传递的是字符串“null”的情况下,SpringMVC出现数据格式转换异常的错误。

2.利用Spring的转换器拦截请求参数判断null映射成想要的结果

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

public class LongConverter implements Converter<String, Long>
{
    @Override
    public Long convert(String from)
    {
        if (StringUtils.isEmpty(from) || "null".equals(from))
        {
            return null;
        }
        return Long.valueOf(from);
    }
}

3.实现WebMvcConfigurer配置自定义的转换器

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Author LiXiangrong
 * @Description 自定义WebConfig
 * @Date 2023/04/23 10:35:27
 **/
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new IntegerConverter());
        registry.addConverter(new LongConverter());
        registry.addConverter(new BigDecimalConverter());
    }
}
0

评论 (0)

取消