Render output format (HTML, JSON, XML) depending on parameter?

前端 未结 3 924
傲寒
傲寒 2020-12-28 09:36

is there a good or proper way to render the output in Play Framework depending on a parameter? Example:

For HTML:

http://lo         


        
3条回答
  •  情书的邮戳
    2020-12-28 10:17

    Write 2 methods, use 2 routes (as you don't specify I will use Java samples:

    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));
    }
    

    routes:

    /GET    /user/get/:id/html     controllers.YourController.userAsHtml(id:Long)
    /GET    /user/get/:id/json     controllers.YourController.userAsJson(id:Long)
    

    next you can just make a link in other view to display user's data

    Show details
    Get JSON
    

    or something else...

    edit #1

    you can also use common if or case to determine final output

    public static Result userAsV() {
        String vType = form().bindFromRequest().get("v");
    
        if (vTtype.equals("HTML")){
            return ok(someView.render(User.find.byId(id)));
        }
    
        return play.libs.Json.toJson(User.find.byId(id));
    }
    

提交回复
热议问题