50

Why is Spring 3.2 only mapping my Boolean based on that the requestparam is "0" or "1" ?

@RequestParam(required= false, defaultValue = "false") Boolean preview

Preview will only be "true" when the requestparam is "?preview=1" which is wierd

I want it to be "?preview=true". How do I do that?

Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42
Tommy
  • 4,011
  • 9
  • 37
  • 59
  • did you know a way, where the request parameter which has default value and required is false, that can be totally ignored in the URL, meaning we don't even have to put anything in the URL for that request parameter. In your example, `preview` will not even be a part of the URL. – Soumitri Pattnaik Jun 16 '16 at 11:37

5 Answers5

106

I think we may need more detail in order to be effective answering your question.

I have working Spring 3.2 code along the lines of:

@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo getFoo(
    @PathVariable("id") String id, 
    @RequestParam(value="bar", required = false, defaultValue = "true")
        boolean bar)
{ 
    ... 
}

Spring correctly interprets ?bar=true, ?bar=1, or ?bar=yes as being true, and ?bar=false, ?bar=0, or ?bar=no as being false.

True/false and yes/no values ignore case.

Tydaeus
  • 1,505
  • 1
  • 13
  • 13
23

Spring should be able to interpret true, 1, yes and on as true boolean value... check StringToBooleanConverter.

Pavel Horal
  • 17,782
  • 3
  • 65
  • 89
0

you can use jackson's JsonDeserialize annotation, short and clean

create the following deserializer:

public class BooleanDeserializer extends JsonDeserializer<Boolean> {
    public BooleanDeserializer() {
    }

    public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return !"0".equals(parser.getText());
    }
}

and add the annotation to your DTO like so:

public class MyDTO {
    @NotNull
    @JsonDeserialize(using = BooleanDeserializer.class)
    private Boolean confirmation;
}
Apex ND
  • 440
  • 5
  • 12
0

We can do using

@GetMapping("/getAudioDetails/organizations/{orgId}/interactions/{interactionId}")
public ResponseEntity<?> getAudioDetails(@PathVariable("orgId") String orgId,@PathVariable("interactionId") String interactionId,
        @RequestParam(name = "verbose", required = false, defaultValue = "false") boolean verbose){
    System.out.println(verbose);
    return null;
}

where verbose is an boolean flag which by default happens to be false as can be referred from inage below on api call .enter image description here

0

I suppose you are missing value="preview" in the @RequestParam. Due to this, Spring is setting the variable preview to false always, as that is the defaultValue.

@RequestParam(value = "preview", required= false, defaultValue = "false") Boolean preview
dj_rai
  • 71
  • 6