如何在Play Framework 2.0 Controller上检索Request body

时间:2014-12-02 17:51:44

标签: java json servlets playframework-2.0 request

我有以下问题:

当我尝试使用https://www.playframework.com/documentation/2.3.x/JavaJsonActions

中显示的示例时

它建议我使用以下声明:

@BodyParser.Of(BodyParser.Json.class)
public static Result sayHello() {
  JsonNode json = request().body().asJson();
  String name = json.findPath("name").textValue();
  if(name == null) {
    return badRequest("Missing parameter [name]");
  } else {
    return ok("Hello " + name);
  }
}

但是当我尝试编译时,我得到一个"无法找到符号"在request()方法。是我还是我忘记了一些导入或方法改变了,我正在查看旧代码?我的代码如下:

package controllers;

import play.*;
import play.mvc.*;
import views.html.*;

import models.Evento;
import models.Pessoa;
import models.Conteudo;
import org.springframework.beans.factory.annotation.Autowired;
import play.data.Form;
import play.libs.Json;
import play.mvc.Result;
import services.EventoService;
import services.PessoaService;
import services.ConteudoService;
import views.html.index;

import java.util.List;

import play.api.Application;
//import org.apache.commons.io.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import play.mvc.BodyParser;

@org.springframework.stereotype.Controller
public class EventApp {

    /* Autowired Classes and other results here */

    @BodyParser.Of(BodyParser.Json.class)
    public Result addEvento() {

        JsonNode json = request().body().asJson();
        Evento evento = new Evento();

        evento.nomeEvento = json.findPath("nomeEvento").textValue();
        evento.dataEvento = json.findPath("dataEvento").textValue();
        evento.enderecoEvento = json.findPath("enderecoEvento").textValue();
        evento.tipoEvento = json.findPath("tipoEvento").intValue();
        evento.perfilEvento = json.findPath("perfilEvento").intValue();
        evento.vCardapio = (char)json.findPath("vCardapio").textValue();
        evento.vPhotoreel = (char)json.findPath("vPhotoreel").textValue();

        if(evento.nomeEvento == null) {
            return play.mvc.Controller.ok("Missing parameter [name]");
        } else {
            return play.mvc.Controller.ok("Json Recebido campeao");
        }

    }


}

1 个答案:

答案 0 :(得分:0)

您可以在此处看到request()方法已定义:https://www.playframework.com/documentation/2.3.x/api/java/play/mvc/Controller.html#request%28%29,因此请确保您的班级(EventApp)正在展开play.mvc.Controller