Play framework 2.0 Form.bindFromRequest().get() re

2019-04-14 14:16发布

I need to receive same POST data from a socket communication.

This is the code that send the POST and receive the response, and seems to work correctly:

String data = "t=" + URLEncoder.encode("Title", "UTF-8") +
    "&u=" + URLEncoder.encode("http://www.myurl.com", "UTF-8");

URL url = new URL("http://localhost:9000/adserver");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output = "Data received\r\n", line;
while ((line = rd.readLine()) != null) {
    output += line;
}
wr.close();
rd.close();

return ok(output);

This is the code that receive the POST:

Form<AdRequest> form = form(AdRequest.class).bindFromRequest();

if(form.hasErrors()) {
    return badRequest("error");
} else {
    AdRequest adr = form.get();
    return ok(adr.t + " - " + adr.u);
}

The AdRequest model is defined in this way:

public class AdRequest {
    public String t;
    public String u;
}

The form object receive the data because I can see them in debug, but the adr object returned by the get() method contains only null values:

adr = {
    t: null,
    u: null
}

Instead, if I use this code to read the data it works correctly:

Map<String, String[]> asFormUrlEncoded = request().body().asFormUrlEncoded();
return ok(asFormUrlEncoded.get("t")[0] + " - " + asFormUrlEncoded.get("u")[0]);

What I'm doing wrong? Is it a Play Framework bug?

Thanks.

1条回答
不美不萌又怎样
2楼-- · 2019-04-14 14:41

The problem for me, it seems, was that Eclipse was interfering with the code generation and generally messing up the generated bytecode.

Turning off "Build Automatically" in Eclipse fixed the problem.

This Link helped: https://groups.google.com/forum/?fromgroups#!topic/play-framework/JYlkz_Nh31g

查看更多
登录 后发表回答