How can my Play 2 app respond to different “Accept” headers from the client?

后端 未结 2 1146
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 23:42

In Rails, I was able to do something similar to the following:

respond_to do |format|
  format.xml { ... }
  format.json { ... }
end

and the ap

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 00:36

    I have just released a Play! 2.0 module for content negotiation called mimerender (http://github.com/martinblech/play-mimerender).

    The idea is that you have to define a mapping from your domain classes to different representations:

    val m = mapping(
      "text/html" -> { s: String => views.html.index(s) },
      "application/xml" -> { s: String => {s} },
      "application/json" -> { s: String => toJson(Map("message" -> toJson(s))) },
      "text/plain" -> identity[String]_
    )
    

    Once you have done that once, you can reuse that mapping throughout all your controllers:

    object Application extends Controller {
      def index = Action { implicit request =>
        m.status(200)("Hello, world!")
      }
    }
    

    Please note it's a very early release and has only been tested on Play 2.0.4

提交回复
热议问题