【问题标题】:Dropwizard example giving 400 error when creating new resource创建新资源时出现 400 错误的 Dropwizard 示例
【发布时间】:2014-04-26 07:17:18
【问题描述】:

我是 Dropwizard 框架的新手。我正在尝试创建一个类似于教程中提到的人员和人员资源的新资源https://github.com/dropwizard/dropwizard/tree/master/dropwizard-example

我正在创建一个这样的文档类 -

@Entity
@Table(name = "document")
@NamedQueries({
        @NamedQuery(
                name = "com.example.helloworld.core.Document.findAll",
                query = "SELECT d FROM Document d"
        ),
        @NamedQuery(
                name = "com.example.helloworld.core.Document.findById",
                query = "SELECT d FROM Document d WHERE d.Id = :Id"
        )
})
public class Document {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long Id;

    @Column(name = "ProcessingSetID")
    private String ProcessingSetID;

    @Column(name = "processed")
    private String processed;

    public long getId() {
        return Id;
    }

    public void setId(long id) {
        this.Id = id;
    }

    public String getProcessingSetID() {
        return ProcessingSetID;
    }

    public void setProcessingSetID(String processingSetID) {
        ProcessingSetID = processingSetID;
    }

    public String getProcessed() {
        return processed;
    }

    public void setProcessed(String processed) {
        this.processed = processed;
    }
}

我的文档道是这样的,

public Optional<Document> findById(Long id) {
    return Optional.fromNullable(get(id));
}

public Document create(Document document) {
    return persist(document);
}

public List<Document> findAll() {
    return list(namedQuery("com.example.helloworld.core.Document.findAll"));
}
}

我正在尝试在我的文档资源上调用 POST 方法,

@Path("/documents")
@Produces(MediaType.APPLICATION_JSON)

public class DocumentsResource {

    private final DocumentDao documentDAO;
    private static final Logger log = LoggerFactory.getLogger(DocumentsResource.class);

    public DocumentsResource(DocumentDao documentDAO) {
        this.documentDAO = documentDAO;
    }

    @POST
    @UnitOfWork
    public Document createDocument(Document document) {
        log.info("inside POST method of document.");
        System.out.println("inside POST method of document.....");
        return documentDAO.create(document);
    }

    @GET
    @UnitOfWork
    public List<Document> listDocuments() {
        return documentDAO.findAll();
    }
}

但是我收到了来自客户请求的 400 响应,请在客户请求下方找到

Client client = Client.create();

WebResource webResource = client.resource("http://localhost:8080/documents");

String input = "{\"processed\":\"new process\",\"ProcessingSetID\":\"new iD\"}";

ClientResponse response = 
        webResource.type("application/json").post(ClientResponse.class, input);

if (response.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatus());
}

我试图调试问题,但调用并没有首先到达 POST 方法。似乎它没有从 JSON 字符串创建文档对象,但我看不出原因。此外,当我直接在我的数据库中进行输入并进行 GET 调用时,会收到与 object 等效的完美 JSON 字符串。

【问题讨论】:

    标签: java json rest dropwizard


    【解决方案1】:

    要获得有关 400 错误的有用信息,请在球衣上注册:

    environment.jersey().register(new JsonProcessingExceptionMapper(true));
    

    它将给出更详细的 400 响应消息,对调试很有用。

    【讨论】:

    • 这是完美的,应该是公认的答案。见鬼,Dropwizard 里面应该是默认开启的...
    【解决方案2】:

    一点背景知识:Dropwizard utilizes Jersey,而 Jersey 是最终给您回复 400 Bad Request 的原因,可能还带有一个模糊而简洁的信息。

    为了查看到底是什么困扰了杰克逊(这反过来又困扰了泽西岛),我首先发送了一个空白(空)JSON 对象并查看它是否被接受(它确实 - 以及 POJO 中的所有字段零初始化)。然后我开始添加字段,发送每个这样的对象,直到我到达有问题的字段(在我的例子中,它是一个 boolean 字段,应该是一个 Boolean)。

    我想我可以在您的 POJO(Document 类)中发现两个困难:

    1. getters/setters should be annotated with @JsonProperty

    2. 尝试将Id 的类型更改为Long(可为空的long)。如果您担心在该字段中获得 null,您可以让 getter 返回零或任何默认值。

    【讨论】:

    • 很高兴您发布了“从空白开始,然后逐步向上”的方法,这让我摆脱了困境
    • 那么,你的有问题的领域是什么?
    • 哦,原来是日期时间字符串的格式。我在日期和时间之间有一个空格。我将其替换为 T 并解决了问题。
    【解决方案3】:

    我遇到了同样的问题。错误被抑制并且未在堆栈跟踪中正确传递。 我所做的是在函数周围添加一个 try catch。然后在异常中添加了一个调试器点。我能够找出确切的原因。

    你可以试试这样的。

    @POST
    @UnitOfWork
    public Document createDocument(Document document) throws Exception{
    ....
    }
    

    在 Exception 类中添加调试器点。您将找出解析失败的确切原因。

    希望我很清楚,它会有所帮助!

    【讨论】:

      【解决方案4】:

      Http 状态 400 表示“错误请求”。实际上,您发送的 json 不是有效的Document。 这反过来意味着你永远无法到达

      @POST
      @UnitOfWork
      public Document createDocument(Document document){}
      

      要解决它,请尝试传递 json:

      String input = "{\"id\":\"123456789\",\"processed\":\"new process\",\"ProcessingSetID\":\"new iD\"}";
      

      123456789 替换为您的实际ID。

      PS。为Document 创建一个 DTO 而不是传递实际的实体可能是一个好主意(取决于您的方案)。

      【讨论】:

        【解决方案5】:

        如果您在 run(...) 方法中的 Dropwizard *Application.java 中注册 Jersey 的 CsrfProtectionFilter,请确保将 X-Requested-By 标头添加到所有状态更改中HTTP 调用(POSTPUT 等)。如果在请求中找不到该标头,服务器将返回 HTTP 400 Bad Request

        【讨论】:

          猜你喜欢
          • 2019-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-23
          • 2012-12-18
          • 2021-01-29
          相关资源
          最近更新 更多