11

I want to trim all the form string fields trim automatically (trailing & leading spaces only)

Suppose if I pass FirstName = " robert " Expected: "robert"

Controller class having following code :

@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);
}  

when I debug the code, It's coming into @InitBinder but not trimming bean class string fields.

VijayD
  • 826
  • 1
  • 11
  • 33
bhanwar rathore
  • 328
  • 1
  • 3
  • 15

3 Answers3

6

To add this feature to all JSON submitted in post and received in RequestBody you can have following WebMvcConfigurer in place.

    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 class as :

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;
    }
}
Ashu
  • 639
  • 6
  • 11
  • I think it is better to extend from StringDeserializer class or use its content as there are special cases that default StringDeserializer handles. See here more details on this: https://stackoverflow.com/questions/6852213/can-jackson-be-configured-to-trim-leading-trailing-whitespace-from-all-string-pr#answer-60876643 – Eugene Maysyuk Apr 03 '20 at 16:55
4

The annotation @InitBinder doesn't work with @RequestBody, you have to use it with the @ModelAttribute annotation

You can find more information in the Spring documentation:

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

mlg
  • 5,248
  • 1
  • 14
  • 17
  • I want form data in JSON format only so i can not use @ModelAttribute annotation . I am making restful api call using spring. – bhanwar rathore Feb 21 '17 at 09:27
  • So you can't do it with the @InitBinder. Check out this link, I think it's the same problem of yours: http://stackoverflow.com/questions/25403676/initbinder-with-requestbody-escaping-xss-in-spring-3-2-4 – mlg Feb 21 '17 at 09:48
-1

Try out the below code:

@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() : "");
    }
});
}
VijayD
  • 826
  • 1
  • 11
  • 33