Playframework - JAVA:获取发布数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26769037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:34:17  来源:igfitidea点击:

Playframework - JAVA : Get Post Data

javaplayframework

提问by Guilherme Soares

What am i doing wrong??

我究竟做错了什么??

I'm trying any ways to get POST data but always don't work. So how it is null execute first condional response is badRequest("Expceting some data").

我正在尝试任何方法来获取 POST 数据,但总是不起作用。那么它如何为空执行第一个条件响应是badRequest("Expceting some data")

Routes

路线

POST   /pedidos/novo    controllers.Pedidos.cadastraPedidoNoBanco

Action in my controller

我的控制器中的操作

@BodyParser.Of(BodyParser.Json.class)
    public static Result cadastraPedidoNoBanco(){
        JsonNode data = request().body().asJson();
        if(data == null){
            return badRequest("Expceting some data");
        } else {
            return ok(data);
        }
    }

Another fail test

另一个失败测试

So this didn't happen any error but I didn't know why the response is that:

所以这没有发生任何错误,但我不知道为什么响应是:

Source

来源

public static Result cadastraPedidoNoBanco(){
    Map<String,String[]> data = request().body().asFormUrlEncoded();
    if(data == null){
        return badRequest("Expceting some data");
    } else {
        String response = "";
        for(Map.Entry value : data.entrySet()){
            response += "\n" + value.getValue();
        }
        return ok(response);
    }
}

Response

回复

[Ljava.lang.String;@5817f93f
[Ljava.lang.String;@decc448
[Ljava.lang.String;@334a5a1c
[Ljava.lang.String;@5661fe92
[Ljava.lang.String;@3b904f8c
[Ljava.lang.String;@7f568ee0
[Ljava.lang.String;@bbe5570

Curl

卷曲

curl "http://localhost:9000/pedidos/novo" -H "Origin: http://localhost:9000" -H "Accept-Encoding: gzip,deflate" -H "Accept-Language: en-US,en;q=0.8,pt-BR;q=0.6,pt;q=0.4" -H "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36" -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "Cache-Control: max-age=0" -H "Referer: http://localhost:9000/pedidos/novo" -H "Connection: keep-alive" -H "DNT: 1" --data "nome_cliente=nj&telefone_cliente=jn&rua_cliente=jkn&num_cliente=kjn&comp_cliente=kjn&cep_cliente=kjn&bairro_cliente=jnk" --compressed

回答by biesior

DynamicFormis more comfortable (nota bene, remove the @BodyParserannotation, you don't need it):
(samples for Play 2.3.x)

DynamicForm更舒服(注意,删除@BodyParser注释,您不需要它):(
Play 2.3.x 的示例)

import play.data.DynamicForm;
import play.data.Form;

public static Result cadastraPedidoNoBanco() {

    DynamicForm form = Form.form().bindFromRequest();

    if (form.data().size() == 0) {
        return badRequest("Expceting some data");
    } else {
        String response = "Client " + form.get("nome_cliente") + "has phone number " + form.get("telefone_cliente");

        return ok(response);
    }
}

Yet better...

然而更好...

option would be creating dedicated Form for your form, so you can validate fields with built-in constraints, types etc, sample form would look like...

选项将为您的表单创建专用表单,因此您可以使用内置约束、类型等验证字段,示例表单看起来像...

app/forms/Pedido.java

应用程序/表单/Pedido.java

package forms;

import play.data.validation.Constraints;

public class Pedido {

    @Constraints.Required()
    @Constraints.MinLength(3)
    public String nome_cliente;

    @Constraints.Required()
    @Constraints.MinLength(9)
    public String telefone_cliente;

    @Constraints.Required()
    public Long some_number;
    //etc...
}

and your action:

和你的行动:

import java.util.List;
import java.util.Map;

import play.data.Form;
import forms.Pedido;
import play.data.validation.ValidationError;
import play.i18n.Messages;

public class Pedidos extends Controller {


    public static Result cadastraPedidoNoBanco() {
        Form<Pedido> form = Form.form(Pedido.class).bindFromRequest();

        if (form.hasErrors()) {
            String errorsMsg = "There are " + form.errors().size() + " errors... \n";

            // Of course you can skip listing the errors
            for (Map.Entry<String, List<ValidationError>> entry : form.errors().entrySet()) {
                String errorKey = entry.getKey();
                List<ValidationError> errorsList = entry.getValue();
                for (ValidationError validationError : errorsList) {
                    errorsMsg += errorKey + " / " + Messages.get(validationError.message()) + "\n";
                }
            }

            return badRequest(errorsMsg);
        }

        Pedido data = form.get();
        String response = "Client " + data.nome_cliente + " has phone number " + data.telefone_cliente;

        return ok(response);
    }

}

On the other hand if your data comes from website form, most often what you want is to render the form again...

另一方面,如果您的数据来自网站表单,通常您想要的是再次呈现表单......

if (form.hasErrors()) {
    return badRequest(views.html.yourViewWithForm.render(form));
}

回答by Guilherme Soares

I could get post value. I discover why "Another test fail" doesn't works. Because Playframework always return a array to me. I only need take first value [0]if i'm only working with unique param.

我可以获得后价值。我发现为什么“另一个测试失败”不起作用。因为 Playframework 总是向我返回一个数组。如果我只使用唯一参数,我只需要取第一个值[0]

Example if I have post param "name"

例如,如果我有帖子参数“名称”

I need do it

我需要做

request().body().asFormUrlEncoded().get("name")[0];