3

when I try to map Boolean value from url to spring controller, it always map to false.

This is my url

http://localhost:8080/myurl?isFirstTime=true

here is my controller

 @RequestMapping(value = "/myurl", method = RequestMethod.GET)
        public ResponseEntity<?>  getMyUrl(@Valid @ModelAttribute MyObject ap,BindingResult bindingResult ) {

//here isFirstTime is always set to false

}

MyObj is POJO and has several other attributes which are mapping perfectly

public class Myobj{

 private boolean isFirstTime
  //there are other members as well
    //getter setter

i tried putting @JsonProperty but that also didn't work

@JsonProperty
private boolean isFirstTime

any idea what am I doing wrong here ?

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
user9735824
  • 1,196
  • 5
  • 19
  • 36

3 Answers3

1

With @ModelAttribute, the object will be initialized:

  • From the model if already added via Model.
  • From the HTTP session via @SessionAttributes.
  • From a URI path variable passed through a Converter.
  • From the invocation of a default constructor.
  • From the invocation of a "primary constructor" with arguments matching to Servlet request parameters; argument names are determined via JavaBeans

In your case, it might relative to the last statement.

You can try 2 way to solve it: - Provide the constructor with the boolean argument in Myobj.java - Add more method to initialize the @ModelAttribute Myobj firstly

@ModelAttribute
public Myobj initObj(@RequestMapping boolean isFirstTime){
     Myobj obj = new MyObj();
     obj.setIsFirstTime(isFirstTime);
     return obj;
}
Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11
0

The most easiest method could be

@RequestMapping(value = "/myurl", method = RequestMethod.GET)
    public ResponseEntity<?>  getMyUrl(@Valid @ModelAttribute MyObject ap,@RequestParam boolean isFirstTime, BindingResult bindingResult ) {

//here isFirstTime is always initialized from incoming request parameters // you can set it ap.isFirstTime(isFirstTime); // or whatever your setter method is

}

Mohammad Anas
  • 320
  • 3
  • 6
0

I stuck at this problem, but I've found that we must use Boolean object instead of boolean primitive type to map boolean value correctly in ModelAttribute

ntv
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 09 '23 at 09:45