7

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.

2
  • If you need one with and without the model and have the same functionality you might need to rethink (part) of your design. Also the model attribute is already optional, a new instance will be created (depending on how you initially created/stored the model attribute). Commented Dec 17, 2014 at 7:10
  • In our case we toggle features so it's helpful Commented Feb 22, 2017 at 5:50

1 Answer 1

3

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";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.