0%

SpringBoot 字符串参数去除头尾空格

  1. URL 和 FORM 表单中的参数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @ControllerAdvice
    public class ControllerStringParamTrimConfig {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    // 构造方法中 boolean 参数含义为如果是空白字符串, 是否转换为 null
    // 即如果为 true, 那么 " " 会被转换为 null, 否者为 ""
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    }
  2. RequestBody 中 JSON 对象参数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    @Configuration
    public class JacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
    .deserializerByType(String.class, new StdScalarDeserializer<String>(String.class) {

    private static final long serialVersionUID = -7069002275820643695L;

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext ctx)
    throws IOException {
    return StringUtils.trimToNull(jsonParser.getValueAsString());
    }
    });
    }
    }
  3. 原文链接

    ghthou:Spring MVC 配置接收 String 参数时自动去除前后空格