在Spring Controller方法中将ModelAttribute设为可选 [英] Making ModelAttribute optional in Spring Controller method

查看:103
本文介绍了在Spring Controller方法中将ModelAttribute设为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义如下的控制器方法-

I have a controller method defined as follows -

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

即使我没有传递ModelAttribute myObj,也如何才能调用上述控制器方法.

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属性已经是可选的.即使您不传递模型属性,也会创建myObj.所以检查

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
}

不起作用.

尝试一下.像这样在myClass中创建一个布尔值

Try this. create a Boolean in myClass like this

private Boolean isGotMyObj = false;

在您的jsp(提交模型属性)中添加这样的隐藏输入

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

这篇关于在Spring Controller方法中将ModelAttribute设为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆