简体   繁体   中英

Making ModelAttribute optional in Spring Controller method

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.

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM