Rest 根据参数呈现输出格式(HTML、JSON、XML)?

Rest 根据参数呈现输出格式(HTML、JSON、XML)?,rest,playframework-2.0,Rest,Playframework 2.0,是否有一种好的或正确的方法根据参数在Play Framework中呈现输出?例如: 对于HTML: http://localhost:9000/user/get/5?v=HTML // should render HTML template http://localhost:9000/user/get/5?v=JSON // should render JSON template 对于JSON: http://localhost:9000/user/get/5?v=HTML // shoul

是否有一种好的或正确的方法根据参数在Play Framework中呈现输出?例如:

对于HTML:

http://localhost:9000/user/get/5?v=HTML // should render HTML template
http://localhost:9000/user/get/5?v=JSON // should render JSON template
对于JSON:

http://localhost:9000/user/get/5?v=HTML // should render HTML template
http://localhost:9000/user/get/5?v=JSON // should render JSON template
我认为请求拦截器可以实现这一点,但我不知道如何开始或从何处开始:-(


或者,编写一个通用的
render方法
,根据请求读取参数和输出,但在我看来这似乎有些过分?

编写2个方法,使用2个路由(因为您没有指定我将使用Java示例:

public static Result userAsHtml(Long id) {
    return ok(someView.render(User.find.byId(id)));
}

public  static Result userAsJson(Long id) {
    return play.libs.Json.toJson(User.find.byId(id));
}
路线:

/GET    /user/get/:id/html     controllers.YourController.userAsHtml(id:Long)
/GET    /user/get/:id/json     controllers.YourController.userAsJson(id:Long)
接下来,您可以在其他视图中创建一个链接来显示用户的数据

<a href="@routes.YourController.userAsHtml(user.id)">Show details</a>
<a href="@routes.YourController.userAsJson(user.id)">Get JSON</a>

如果
/user/5?v=html
/user/5?v=json
返回同一资源的两种表示形式,则它们应该是相同的URL,例如根据

在客户端,您可以在请求中使用
Accept
头来指示希望服务器向您发送的表示形式

在服务器端,您可以使用Play 2.1编写以下内容来测试
Accept
头的值:

公共静态结果用户(长id){
User=User.find.byId(id);
if(user==null){
返回notFound();
}
if(request()接受(“text/html”)){
返回ok(views.html.user(user));
}else if(request()接受(“application/json”)){
返回ok(Json.toJson(user));
}否则{
返回请求();
}
}
请注意,针对
“text/html”
的测试应始终在任何其他内容类型之前编写,因为浏览器将其请求的
接受
头设置为与所有类型匹配的
*/*

如果您不想在每个操作中编写
If(request().accepts(…)
,您可以将其分解,例如,如下所示:

公共静态结果用户(长id){
User=User.find.byId(id);
返回表示(user,views.html.user.ref);
}
公共静态结果用户(){
List users=User.find.all();
返回表示(users,views.html.users.ref);
}
私有结果表示(T资源,Template1 html){
if(资源==null){
返回notFound();
}
if(request()接受(“text/html”)){
返回ok(html.apply(resource));
}else if(request()接受(“application/json”)){
返回ok(Json.toJson(resource));
}否则{
返回请求();
}
}

我希望用户能够在浏览器中以html或json的形式查看,因此accepts方法对我不起作用

我通过在基类中使用以下样式语法放置一个通用的renderMethod来解决这个问题

public static Result requestType( )
{
    if( request().uri().indexOf("json") != -1)
    {
        return ok(Json.toJson(request()));
    }
    else 
    {
        return ok("Got HTML request " + request() );
    }
}

这可能行得通,但复制东西不是我的第一选择。我对此没有直接的用例,但在将来,如果我想制作一个本地移动应用程序,我想做一个请求,只检索JSON…好的,我想我还想再做一个。但是如何绑定到基于HTML表单或JSON对象的Java对象呢(从请求中),我还需要使用if/else语句来实现它们,或者
bindFromRequest
是否同时提供这两种服务?
bindFromRequest
使用查询字符串和请求体(可以是JSON、url表单编码等)。