gpt4 book ai didi

java - 在 Spring Controller 方法中使 ModelAttribute 可选

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:27 24 4
gpt4 key购买 nike

我有一个 Controller 方法定义如下 -

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

即使我没有传递 ModelAttribute myObj,我怎样才能调用上面的 Controller 方法。

我不想在没有它的情况下创建另一个 Controller 并复制功能。

最佳答案

模型属性已经是可选的。即使您不传递模型属性,也会创建 myObj。所以检查

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

将不起作用。

试试这个。像这样在 myClass 中创建一个 boolean 值

private Boolean isGotMyObj = false;

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

<input type="hidden" value="1" name="isGotMyObj" />

然后在 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";
}

关于java - 在 Spring Controller 方法中使 ModelAttribute 可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27519927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com