In my Controller, I have
@RequestParam boolean flag
This allows the caller of my API to pass "true", "yes", "on" or "1" to represent true.
However, I want to access this flag in my HandlerInterceptor
too. There, all I have is an HttpServletRequest
, and I have to access my flag as
boolean flag = Boolean.parseBoolean(request.getParameter("flag"));
This is not ideal, because parseBoolean
only considers the string "true" to be true. If the API caller passes "yes", "on" or "1" then the interceptor will treat the value as false and the controller will treat it as true.
I don't want to hard code into my application the string values that Spring considers true, because if they change in a future release we are back to square 1.
Is there a way to get consistent boolean value in both interceptor and controller?
CodePudding user response:
I don't think there is way to interpret boolean value in the manner you are expecting. See this answer for more details.
But you can set system properties which can map all possible key's to true something like:
System.setProperty("true", "true");
System.setProperty("one", "true");
System.setProperty("1", "true");
System.setProperty("yes", "true");
boolean b = Boolean.getBoolean("yes");
System.out.println(b);
In this way, if you received different key value than above false will be returned as boolean value.
CodePudding user response:
Found the answer to my question and posting it here for future readers.
To get the exact same conversion in the interceptor as happens in the controller, you should use the same Spring method:
boolean flag = DefaultConversionService.getSharedInstance().convert(
request.getParameter("flag"),
Boolean.class);
Note that if request.getParameter("flag") returns null or some string that doesn't represent a boolean, convert
will throw an exception.