How to automatically crop rows of bean object in spring using Restful api?

I want to trim all string fields with a form string automatically (only for trailing and leading spaces)

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

A controller class that has the 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 goes into @InitBinder but does not crop the fields of the bean line.

+5
source share
2 answers

@InitBinder annotation @InitBinder not work with @RequestBody , you should use it with @ModelAttribute annotation

You can find more information in the Spring documentation:

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

+1
source

Try the code below:

 @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() : ""); } }); } 
0
source

Source: https://habr.com/ru/post/1264494/


All Articles