java - 如何将表单字段绑定(bind)到 Play 2 Framework 中的对象

标签 java playframework-2.0

我一直无法让我的表单绑定(bind)正常工作(基本上是反复试验)。 在 Play 2.0.3 (Java) 中,将表单绑定(bind)到由其他对象组成的模型的正确方法是什么?

我编写了这个小例子来尝试更好地理解它。 但即使是这个基本的例子似乎也有问题。

我尝试将表单绑定(bind)到的 Simple 类有 3 个字段:一个普通字符串字段、一个字符串列表和一个自定义字段(它只是字符串的包装器)。 提交表单后,所有字段均已填充,但自定义字段仍为空。

这是实际代码

Controller

static Form<Simple> simpleform=form(Simple.class);
public static Result simpleForm(){
Form<Simple> filledForm=simpleform.bindFromRequest();
        System.out.println(filledForm);
    return ok(views.html.simpleForm.render(filledForm.get().toString()));
}

型号

public class Simple {
    public String text;
    public List<String> stringList;
    public SimpleWrapper wrappedText;
    @Override
    public String toString(){
        return text +"-"+simpleWrapper+"-"+stringList;
}

public  class SimpleWrapper{
        String otherText;
        public SimpleWrapper(){}
        public SimpleWrapper(String otherText){
            this.otherText=otherText;
        }
        @Override
        public String toString(){
            return otherText;
        }
    }

查看

@(text:String)
@import helper._
@form(routes.Management.simpleForm()){
  <input type="hidden" value="string" name="stringList[0]">
  <input type="hidden" value="stringAgain" name="stringList[1]">
  <input type="hidden" value="wrapped" name="wrappedText.otherText">
  <input type="text" id="text" name="text">
  <input type="submit" value="submit">
}
This was passed @text

最佳答案

为了允许自动绑定(bind)对象,您必须为您的类提供一个 setter 方法。在我的实验中,SimpleWrapper 类缺少该类应该具有的 setter 方法

public  class SimpleWrapper{
    String otherText;
    public SimpleWrapper(){}

    public setOtherText(String otherText){
     this.otherText=otherText;
    }

    @Override
    public String toString(){
        return otherText;
    }
}

看起来甚至构造函数也无关紧要。

这是一个关于底层 Spring 数据绑定(bind)器的链接 link这可能会有所帮助。我从 play google 小组得到的

关于java - 如何将表单字段绑定(bind)到 Play 2 Framework 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12743404/

相关文章:

java - 使用 Java Web Start

scala - 在 Play Framework 中更改自定义文件时重新加载应用程序

java - Play 框架 2.0.1 - 服务器仅响应第一个请求

playframework - 在路由中传递参数值?

java - 忽略返回对象时的编译时警告

java - AVL树,java,继任者,前任

java - Spring : Logging wont get disabled. 默认转为 Debug

java - Android Function 返回一个数组直接变成变量

module - 无法下载Play框架2的依赖项Elasticsearch

java - Play2.0 返回 "SQLException: Timed out waiting for a free available connection."