Mohan Krishnan
Mohan Krishnan

Reputation: 353

Spring - Handling null values in Request Parameters

In Spring (4.3.9):

A Request param sent from client as null to server, the null object is getting treated as string null in the request when obtained via request-param like:

@RequestParam(value = key, required = false) Integer key

As for as the solution goes, I can handle this via client and prevent the null from being passed in the first place and I couldn't get a clear solution from this (JavaScript: Formdata append null value - NumberFormatException).

Can anyone please help me out as to what class or method in spring framework does this conversion from a null object to string null.

Upvotes: 4

Views: 7285

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

Whatever the content you provide for the @RequestParam by default it will treat as string, that is the reason null is treating as "null" string. In the spring framework the Converter<S, R> and ConverterFactory<S, R> will convert from String to corresponding type.

You can write custom converter and add it to spring registry here

public class StringToIntegerConverter implements Converter<String, Integer> {

@Override
public Integer convert(String from) {
    // custom logic
   }
}

register

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new StringToIntegerConverter());
       }
 }

Upvotes: 3

Related Questions