获取后期数据播放框架(Java)
我有一个带有POST路由的Play应用程序,它将充当RESTful API 在控制器内获取POST数据的最佳方法是什么?正如您从我的控制器中看到的,我已经尝试过这样做,但是它似乎无法正常工作 路线:获取后期数据播放框架(Java),java,rest,post,playframework,playframework-2.0,Java,Rest,Post,Playframework,Playframework 2.0,我有一个带有POST路由的Play应用程序,它将充当RESTful API 在控制器内获取POST数据的最佳方法是什么?正如您从我的控制器中看到的,我已经尝试过这样做,但是它似乎无法正常工作 路线: # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET / controllers
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
GET /api/getMessages controllers.Application.getMessages()
POST /api/createMessage controllers.Application.createMessages()
控制器:
package controllers;
import play.*;
import play.mvc.*;
import static play.libs.Json.toJson;
import java.util.Map;
import models.*;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result createMessages(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
String from = values.get("from")[0];
String subject = values.get("subject")[0];
String message = values.get("message")[0];
Message.create(from, subject, message);
return ok(toJson("ok"));
}
public static Result getMessages(){
return ok(toJson(Message.all()));
}
}
尝试使用DynamicForm:
public static Result createMessages(){
DynamicForm df = play.data.Form.form().bindFromRequest();
String from = df.get("from");
String subject = df.get("subject");
String message = df.get("message");
if(from != null && subject != null && message != null){
Message.create(from, subject, message);
return ok(toJson("ok"));
} else {
return ok(toJson("error"));
}
}
尝试使用DynamicForm:
public static Result createMessages(){
DynamicForm df = play.data.Form.form().bindFromRequest();
String from = df.get("from");
String subject = df.get("subject");
String message = df.get("message");
if(from != null && subject != null && message != null){
Message.create(from, subject, message);
return ok(toJson("ok"));
} else {
return ok(toJson("error"));
}
}
我很确定作者已经找到了这两年的解决方案:),但今天我遇到了同样的麻烦,也许我的细微差别会帮助某些人: 我使用相同的方法获取POST参数:
request().body().asFormUrlEncoded().get("from")[0];
我也犯了错误。但错误是因为不同的帖子类型。所以在我的例子中,我只需要期望多部分表单数据,如下一个变体:
request().body().asMultipartFormData().asFormUrlEncoded().get("from")[0];
所以-只需对您发送的数据和您期望的数据更加小心一点:)我很确定作者已经找到了这两年的解决方案:),但今天我遇到了同样的问题,我的细微差别可能会帮助某些人: 我使用相同的方法获取POST参数:
request().body().asFormUrlEncoded().get("from")[0];
我也犯了错误。但错误是因为不同的帖子类型。所以在我的例子中,我只需要期望多部分表单数据,如下一个变体:
request().body().asMultipartFormData().asFormUrlEncoded().get("from")[0];
所以-只需对正在发送的数据和期望的数据更加小心:)错误消息是什么?返回的错误是null错误消息是什么?返回的错误是null顺便说一句。form()已被弃用。form()已弃用