1

如何验证 POST 请求的 @FormParams 不为空?我们使用的是 Dropwizard 0.9.3 版。

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response addCard(@FormParam("title") @NotEmpty String title,
                        @FormParam("latitude") @NotNull Double latitude,
                        @FormParam("longitude") @NotNull Double longitude,
                        @FormParam("public") @NotNull Boolean publicCard,
                        @FormParam("user_id") @NotNull Integer userId) {

发送不带标题参数的 POST 请求会产生以下服务器错误:

!org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:找不到媒体类型 = 文本/html、类型 = 类 io.dropwizard.jersey.validation.ValidationErrorMessage、genericType = 类 io.dropwizard.jersey.validation.ValidationErrorMessage 的 MessageBodyWriter。

客户收到:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Error 500 Request failed.</title>
</head>
<body>
    <h2>HTTP ERROR 500</h2>
    <p>Problem accessing /cards. Reason:

        <pre>    Request failed.</pre>
    </p>
    <hr>
        <i>
            <small>Powered by Jetty://</small>
        </i>
        <hr/>
    </body>
</html>

以前我使用@NotEmpty 为@QueryParam 并且效果很好。我希望客户收到类似(400 Bad request)的信息:

{
"errors": [
    "query param title may not be null",
]
}

我尝试过使用 dropwizard 0.9.0 中引入的 NonEmptyStringParam,但这没有用。有什么建议么?

编辑:

文档说明如下:“如果您有需要验证的可选字段或参数,请在其上添加 @UnwrapValidatedValue 注释。” 和“如果您希望 q 在这种情况下评估为 Optional.absent(),请将类型更改为 NonEmptyStringParam”。我已经尝试过了,但没有对参数进行评估。

4

1 回答 1

2

您希望响应以 json 形式出现。您需要produces在您的方法之上添加。

@Produces(MediaType.APPLICATION_JSON) 

这应该可以解决您的问题。

于 2016-07-14T15:34:22.783 回答