Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playframework - JAVA : Get Post Data

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").

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
like image 722
Guilherme Soares Avatar asked Dec 02 '22 18:12

Guilherme Soares


1 Answers

DynamicForm is more comfortable (nota bene, remove the @BodyParser annotation, you don't need it):
(samples for 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

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));
}
like image 149
biesior Avatar answered Dec 18 '22 02:12

biesior