You can test if request().accepts("application/json“)
but checking with if-else for every content-type seems to be the standard way.
How to have different representations in Play based on an Accept header?
-
05-07-2023 - |
题
Using Play Framework 2.1, and I'd like to make small variations in behavior based on the request's Accept header. The only thing I can figure to do is this:
conf/routes
GET /widgets controllers.WidgetController.getWidgets()
WidgetController.java
public class LoginController extends Controller {
public static Result loginUser() {
if (ctx().request().headers().get("Accept")[0].equals("application/json")) {
// ... json-specific logic
}
// common processing code
if (ctx().request().headers().get("Accept")[0].equals("application/json")) {
return ok();
} else {
return redirect(...);
}
}
}
Seems very nasty and procedural. Any suggestions on the idiomatic "Play" way to do this?
解决方案
不隶属于 StackOverflow