Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 379
Novice User Avatar asked Aug 12 '26 10:08

Novice User


1 Answers

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";
}
like image 142
gladis Avatar answered Aug 15 '26 00:08

gladis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!