【问题标题】:how to Auto Trim Strings of bean object in spring with Restful api?如何在 Spring 中使用 Restful api 自动修剪 bean 对象的字符串?
【发布时间】:2026-02-03 15:00:01
【问题描述】:

我想自动修剪所有表单字符串字段(仅限尾随和前导空格)

假设如果我通过 FirstName = "robert " 预期:“罗伯特”

具有以下代码的控制器类:

@InitBinder
public void initBinder ( WebDataBinder binder )
{
    StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true);  
    binder.registerCustomEditor(String.class, stringtrimmer);
}

@RequestMapping(value = "/createuser", method = RequestMethod.POST)
public Boolean createUser(@RequestBody  UserAddUpdateParam userAddUpdateParam) throws Exception {

    return userFacade.createUser(userAddUpdateParam);
}  

当我调试代码时,它会进入@InitBinder,但不会修剪 bean 类字符串字段。

【问题讨论】:

    标签: java spring rest


    【解决方案1】:

    注解@InitBinder 不适用于@RequestBody,您必须将其与@ModelAttribute 注解一起使用

    您可以在 Spring 文档中找到更多信息:

    https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html

    【讨论】:

    • 我只想要 JSON 格式的表单数据,所以我不能使用 @ModelAttribute 注释。我正在使用 spring 进行宁静的 api 调用。
    • 所以你不能用@InitBinder 来做。看看这个链接,我想你的问题是一样的:*.com/questions/25403676/…
    【解决方案2】:

    要将此功能添加到所有在 post 中提交并在 RequestBody 中接收的 JSON,您可以使用以下 WebMvcConfigurer。

        import java.util.List;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.http.converter.HttpMessageConverter;
        import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
        import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
        import com.fasterxml.jackson.databind.DeserializationFeature;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import com.fasterxml.jackson.databind.module.SimpleModule;
    
        @Configuration
        public class HttpMessageConvertor implements WebMvcConfigurer {
    
        @Override
        public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(mappingJackson2HttpMessageConverter());
        }
    
        @Bean
        public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
            MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
            SimpleModule module = new SimpleModule();
            module.addDeserializer(String.class, new StringWithoutSpaceDeserializer(String.class));
            mapper.registerModule(module);
    
            converter.setObjectMapper(mapper);
    
            return converter;
        }
    }
    

    StringWithoutSpaceDeserializer 类为:

    import java.io.IOException;
    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
    
    public class StringWithoutSpaceDeserializer extends StdDeserializer<String> {
        /**
         * 
         */
        private static final long serialVersionUID = -6972065572263950443L;
    
        protected StringWithoutSpaceDeserializer(Class<String> vc) {
            super(vc);
        }
    
        @Override
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return p.getText() != null ? p.getText().trim() : null;
        }
    }
    

    【讨论】:

    • 我认为最好从 StringDeserializer 类扩展或使用它的内容,因为存在默认 StringDeserializer 处理的特殊情况。请参阅此处的更多详细信息:*.com/questions/6852213/…
    【解决方案3】:

    试试下面的代码:

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
    
    dataBinder.registerCustomEditor(String.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            if (text == null) {
                return;
            }
            setValue(text);
        }
    
        @Override
        public String getAsText() {
            Object value = getValue();
            return (value != null ? value.trim().toString() : "");
        }
    });
    }
    

    【讨论】: