Making ModelAttribute optional in Spring Controlle

2019-06-26 07:55发布

问题:

I have a controller method defined as follows -

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

How can I make the above controller method to be called even when I do not passed the ModelAttribute myObj.

I do not want to create another controller without it and duplicate the functionality.

回答1:

Model attribute is already optional. Even if you do not pass model attribute, myObj is created. So checking

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

will not work.

Try this. create a Boolean in myClass like this

private Boolean isGotMyObj = false;

In your jsp which (submits model attribute) add a hidden input like this

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

then perform this in 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";
}