gpt4 book ai didi

java - 如何在 play-framework 2.0 中绑定(bind)复杂类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:52 27 4
gpt4 key购买 nike

我有一个具有以下结构的模型类:

public class User {
public String name;
public Long id;
}

public class Play {
public String name;
public User user;
}

现在我想要一个基于 Play 类的表单。所以我有一个 editPlay View ,它将 Form[Play] 作为输入。在 View 中,我有一个表单调用提交时的更新操作:

@form (routes.PlayController.update()) 
{..}

但我找不到正确的方式来绑定(bind)用户字段,我会在 Controller 中正确接收它:

Form<Play> formPlay = form(Play.class).bindFromRequest();
Play playObj = formPlay.get();

根据API , Form.Field 值始终是一个字符串。有没有其他方法可以自动将输入绑定(bind)到用户对象?

谢谢

最佳答案

您可以使用自定义 DataBinder在 play.scla.html 中:

@form (routes.PlayController.update()) 
{
<input type="hidden" name="user" id="user" value="@play.user.id"/>
}

在 Controller 中的方法中

public static Result update()
{
// add a formatter which takes you field and convert it to the proper object
// this will be called automatically when you call bindFromRequest()

Formatters.register(User.class, new Formatters.SimpleFormatter<User>(){
@Override
public User parse(String input, Locale arg1) throws ParseException {
// here I extract It from the DB
User user = User.find.byId(new Long(input));
return user;
}

@Override
public String print(User user, Locale arg1) {
return user.id.toString();
}
});
Form<Play> formPlay = form(Play.class).bindFromRequest();
Play playObj = formPlay.get();
}

关于java - 如何在 play-framework 2.0 中绑定(bind)复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8729444/

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