문제

또는 적절한 방법을 렌더링하는 출력에서 플레이에 따라 매개 변수는?예제:

HTML:

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

JSON:

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

내가 생각하는 요청을 요격할 수 있는 능력이 있는 이것을 달성하기 위해,그러나 나는 아무 단서를 어떻게 시작하거나 시작하는 곳:-(

아니면,성 render method 읽어주는 매개변수를 출력 요청에 따라,그러나 이것은 저 같은 과잉?

도움이 되었습니까?

해결책

는 경우 /user/5?v=html/user/5?v=json 반 두 가지 표현의 동일한 자원,그들은 동일해야한 URL,예를 들어, /user/5, 에 따라, 나머지 원칙.

클라이언트 측에서 사용할 수 있습니다 Accept 헤더에서 당신의 요구를 나타내는 표현할 서버가 보내드립니다.

서버 측에서 작성할 수 있습니다 다음으로 플레이 2.1 의 값을 테스트 Accept 헤더:

public static Result user(Long id) {

  User user = User.find.byId(id);
  if (user == null) {
    return notFound();
  }

  if (request().accepts("text/html")) {
    return ok(views.html.user(user));
  } else if (request().accepts("application/json")) {
    return ok(Json.toJson(user));
  } else {
    return badRequest();
  }
}

참고에 대한 테스트 "text/html" 항상 기록하기 전에 다른 어떤 콘텐츠 형식이기 때문에 브라우저로 설정 Accept 헤더의 자신의 요청 */* 과 일치하는 모든 종류.

당신이 원하지 않는 경우 쓰기 if (request().accepts(…)) 에서 각 작업할 수 있는 요인이 그것을 밖으로,예를 들어,다음과 같:

public static Result user(Long id) {
  User user = User.find.byId(id);
  return representation(user, views.html.user.ref);
}

public static Result users() {
  List<User> users = User.find.all();
  return representation(users, views.html.users.ref);
}

private <T> Result representation(T resource, Template1<T, Html> html) {
  if (resource == null) {
    return notFound();
  }

  if (request().accepts("text/html")) {
    return ok(html.apply(resource));
  } else if (request().accepts("application/json")) {
    return ok(Json.toJson(resource));
  } else {
    return badRequest();
  }
}

다른 팁

쓰 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>

또는 다른...

편집#1

사용할 수도 있습니다 일반 ifcase 을 결정하는 최종 출력

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

내가 원할 수 있도록 사용자를 볼 수 있는 브라우저에서는 html 또는 json 으로 그래서 가지 방법을 작동하지 않았습니다.

나는 그것을 해결해 일반 renderMethod 기본 클래스에서 다음과 같은 문법

public static Result requestType( )
{
    if( request().uri().indexOf("json") != -1)
    {
        return ok(Json.toJson(request()));
    }
    else 
    {
        return ok("Got HTML request " + request() );
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top