gpt4 book ai didi

java - SpringFramework 自定义绑定(bind)类型参数

转载 作者:行者123 更新时间:2023-12-01 12:15:59 25 4
gpt4 key购买 nike

我想将自定义对象/接口(interface)实现绑定(bind)到我的 Controller 。

class Form{
private Action action;
// setter/getter
}

interface Action{}

class Action1 implements Action{}

class Action2 implements Action{}


@Controller
class ActionController{
@RequestMapping("/")
public String action(Form form){
form.getAction(); // this should be an instance of Action1 or Action2
}
}

为了确定它是 Action1 还是 Action2,我想向 HTML 表单添加一个类型参数。

<input name="form.action.type" value="1" />

是否有类似的东西已经可用,或者有人知道如何实现它。

我已经看过 PropertyEditors,但据我所知,您只能获得一个字符串字段,而且似乎无法访问任何其他属性。如果可能的话,我正在寻找一种比创建自己的 HandlerMethodArgumentResolver 更简单的方法

最佳答案

您将无法完全做到这一点。当 Controller 声明 ModelAttribute 参数时,Spring 首先创建一个空对象并设置其参数或其子对象的参数。因此在分析 form.action.type 参数之前必须创建一个 Action 对象。

一种方法是使用默认的 Action 实现,该实现将能够直接接受所有表单参数。然后 getter 将生成正确的 Action 类型。

private class ActionDefault {
// parameters and setters to store all form fields at appropriate level
}

class Form {
Action action = null;
ActionDefault actionDefault = new ActionDefault();

Action getAction() {
if (action == null) {
// generates proper Action object and affects it to action
}
return action;
}
// getter and setter for actionDefault;
}

关于java - SpringFramework 自定义绑定(bind)类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27011858/

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