4

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.

Mohan Krishnan
  • 353
  • 3
  • 16
  • You're looking for `HttpMessageConverter` and the `Converter` framework generally, but you haven't really described enough of your case to understand if there's an underlying problem (for example, it's not clear whether you mean `s == null` or `s.equals("null")`). Including an actual HTTP request would be helpful. – chrylis -cautiouslyoptimistic- Nov 08 '18 at 19:54

1 Answers1

2

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());
       }
 }
Neuquino
  • 11,580
  • 20
  • 62
  • 76
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • Thanks for the info.The converter you pointed out converts the string to the desired type mentioned in the @RequestParam, but can you point me where does the null object passed from client is getting converted to string null. --------------------------------------------------------------------------------------------------------- I could see that when i do request.getParameter("key") it return me string null ("null") in my first filter itself. So am assuming this conversion happens in the apache http layer. I just need to know the class file , method that parses this. – Mohan Krishnan Nov 08 '18 at 20:07
  • i'm not sure to that point, may be front controller is the main point of request – Ryuzaki L Nov 08 '18 at 20:14
  • Thanks for the prompt help. I'll just handle this client to avoid issues for now and also i'll keep this open for better explanation. – Mohan Krishnan Nov 08 '18 at 20:21