Shashi Shekhar
Shashi Shekhar

Reputation: 307

Spring command object throws NumberFormatException for integer field if form fields contain space

Is there a way to write a common code or a configuration which can remove trailing or leading spaces from any strings which are input from form submission in web application so that we should not get NumberFormatException at java code level while parsing those strings to Integer or number. For example " 15246 ". Because in case of spring command object if it has a integer field then it tries to convert it into integer implicitly. Except IE browser other browser do not let number field has leading or trailing space.

Upvotes: 0

Views: 95

Answers (2)

Martin van Wingerden
Martin van Wingerden

Reputation: 981

If you use Spring-Boot 2 it will just work out of the box:

Test.java

package hello;

public class Test {
    private Integer test;

    public Integer getTest() {
        return test;
    }

    public void setTest(Integer test) {
        this.test = test;
    }

    @Override
    public String toString() {
        return "Test{test=" + test + '}';
    }
}

TestController.java

package hello;

@RestController
public class TestController {
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String testGet(@RequestParam("test") Integer integer) {
        return "" + integer;
    }

    @RequestMapping(value = "/test_p", method = RequestMethod.POST)
    public String testPost(@RequestBody Test test) {
        return "" + test;
    }
}

Test the POST with curl

curl -X POST \
  http://localhost:8080/test_p \
  -H 'Content-Type: application/json' \
  -d '{"test": " 876867"}'

Test{test=876867}

Test the GET with curl

curl -X GET \
  'http://localhost:8080/test?test=%20542543' \
  -H 'Content-Type: application/json' \

542543

The reason this works originates from the class StringToNumberConverterFactory

Which uses NumberUtils which indeed trims all whitespace

String trimmed = StringUtils.trimAllWhitespace(text);

Upvotes: 1

bNd
bNd

Reputation: 7630

Try with java inbuilt trim method

" 15246".trim()

Then cast into Integer.valueOf(" 15246".trim())

Upvotes: 2

Related Questions