简体   繁体   中英

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.

Whatever the content you provide for the @ReuqestParam 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());
       }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM