请求如何在Play Framework 2中运行?

时间:2012-04-25 08:22:50

标签: json request playframework-2.0

我必须说我对如何使用新的Play Framework 2处理请求参数感到有些困惑。数据来自关于如何发出请求的不同来源。到目前为止,这里有可能性:

1 - 如果你做一个简单的GET:

ctx().request().queryString()

2 - 如果您使用HTML表单执行POST:

表格:

<form method="post" action="/">
    <input type="hidden" name="foo" value="bar" />
    <input type="hidden" name="t" value="1" />
    <input type="hidden" name="bool" value="true" />
    <input type="submit" name="submit" value="Submit" />
</form>

方法:

public static Result test() {
    ctx().request().queryString();             // {} ; As expected
    ctx().request().body();                    // contains data
    ctx().request().body().asFormUrlEncoded(); // contains data
    ctx().request().body().asJson();           // empty
    return ok();
}

这似乎很正常。

现在,如果我添加@BodyParser.Of(BodyParser.Json.class)(假设我在非JS案例中接受Ajax POST和普通POST以进行后退):

@BodyParser.Of(BodyParser.Json.class)
public static Result test() {
    ctx().request().queryString();             // {} ; as Expected
    ctx().request().body();                    // contains data
    ctx().request().body().asFormUrlEncoded(); // empty : Shouldn't this contains data since I posted them via a simple form ?!
    ctx().request().body().asJson();           // empty
    return ok();
}

然后,地狱受到了影响:如果没有填充它们,我怎么能得到一个简单形式的值(asJson,asFormUrlEncoded等)?!

3 - 如果你通过AJAX进行POST:

// Code in JS used :
$.ajax({
    'url': '/',
    'dataType': 'json',
    'type': 'POST',
    'data': {'foo': 'bar', 't': 1, 'bool': true}
});

结果:

public static Result test() {
    ctx().request().queryString();             // {}
    ctx().request().body();                    // contains data
    ctx().request().body().asFormUrlEncoded(); // contains data
    ctx().request().body().asJson();           // empty
    return ok();
}

使用@BodyParser.Of(BodyParser.Json.class)

@BodyParser.Of(BodyParser.Json.class)
public static Result test() {
    ctx().request().queryString();             // {}
    ctx().request().body();                    // contains data
    ctx().request().body().asFormUrlEncoded(); // empty
    ctx().request().body().asJson();           // empty : Shouldn't this contains data since I espect JSON ?!
    return ok();
}

这里的不一致是应该返回数据的asJson()方法,因为根据文档

  

注意:这样,对于非JSON请求,将自动返回400 HTTP响应。 (http://www.playframework.org/documentation/2.0/JavaJsonRequests)

我想知道的是什么是POST的最佳装饰器+方法,它接受来自HTML的简单帖子或带有POST的Ajax请求?

2 个答案:

答案 0 :(得分:7)

我建议使用PlayFramework提供的Form类。 表单将其值绑定到提供的请求数据。

有两种不同的Form实现:

  1. DynamicForm:POST数据可通过Map访问器方法获得
  2. 表单:Form的通用形式将POST数据映射到实体类的实例[more information]

    该表单还提供了一些有用的功能,如自动类型转换,验证,错误报告等。

  3. 动态表单的简单示例:

    ajax请求:

    $.post("@routes.Application.movetodo()", 
        { "id": 123, "destination": destination }, function(data)
            {
               // do something when request was successfull
            });
    

    路由文件:

    GET     /                           controllers.Application.index()
    POST    /movetodo                   controllers.Application.movetodo()
    

    控制器实施:

    public static Result movetodo()
    {
        DynamicForm data = form().bindFromRequest(); // will read each parameter from post and provide their values through map accessor methods
        // accessing a not defined parameter will result in null
        String id = data.get("id");
        String destination = data.get("destination");
    
        return ok();
    }
    

答案 1 :(得分:0)

asJson()为空的原因是默认情况下, $。ajax 会发送内容类型设置为&#39; application / x-www-的请求窗体-urlencoded;字符集= UTF-8&#39; 即可。您需要将其设置为&#39; application / json;字符集= UTF-8&#39;

$.ajax({
    contentType: "application/json; charset=utf-8",
    ...
})