删除向导验证@FormParam



如何验证 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、类型=类的 MessageBodyWriter io.dropwizard.jersey.validation.ValidationErrorMessage, 泛型类型=类 io.dropwizard.jersey.validation.ValidationErrorMessage.

客户收到:

<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 错误请求)的内容:

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

我尝试使用dropwizard 0.9.0中引入的非空字符串参数但这没有用。有什么建议吗?

编辑:

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

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

@Produces(MediaType.APPLICATION_JSON) 

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

最新更新