简体   繁体   English

在Spring Controller方法中使ModelAttribute可选

[英]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. 即使我没有通过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. 即使您没有传递模型属性,也会创建myObj。 So checking 所以检查

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

will not work. 不管用。

Try this. 试试这个。 create a Boolean in myClass like this 像这样在myClass中创建一个布尔值

private Boolean isGotMyObj = false;

In your jsp which (submits model attribute) add a hidden input like this 在你的jsp中(提交模型属性)添加这样的隐藏输入

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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