Providing ModelAttribute Option in Spring Controller Method

I have a controller method defined like this:

@RequestMapping(method = RequestMethod.POST, value="/callMe")
public String myMethod(@ModelAttribute MyClass myObj, Model model) {
    //Do something
}

      

How can I call the above controller method even if I haven't passed the ModelAttribute to myObj.

I don't want to create another controller without it and duplicate functionality.

+3


source to share


1 answer


The model attribute is already optional. Even if you don't pass the model attribute, myObj is created. Therefore, checking

if(myObj == null){
   //Do method1
}else{
  //Do method2
}

      

will not work.

Try it. create a boolean in myClass

private Boolean isGotMyObj = false;

      



In jsp that (passes the model attribute) add hidden input like this

<input type="hidden" value="1" name="isGotMyObj" />

      

then do this in your controller

@RequestMapping(method = RequestMethod.POST, value="/callMe")
public String myMethod(@ModelAttribute MyClass myObj, Model model) {
    if (myObj.getIsGotMyObj()){
        //Got model attribute
        //Method 1
    }else{
        //Method 2
    }

    return "callme";
}

      

+2


source







All Articles