Dropwizard验证@FormParam

时间:2016-07-13 10:14:47

标签: validation jersey dropwizard javax.ws.rs

如何验证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!   找不到媒体类型= text / html,type = class的MessageBodyWriter   io.dropwizard.jersey.validation.ValidationErrorMessage,   genericType =类   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 Bad request)的内容:

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

我尝试过使用dropwizard 0.9.0中引入的NonEmptyStringParam 但那并没有奏效。有什么建议吗?

编辑:

文档说明如下:&#34;如果您有一个需要验证的可选字段或参数,请在其上添加@UnwrapValidatedValue注释。&#34;和&#34;如果您希望q在这种情况下评估为Optional.absent(),请将类型更改为NonEmptyStringParam&#34;。我试过这个,但参数没有被评估。

1 个答案:

答案 0 :(得分:1)

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

@Produces(MediaType.APPLICATION_JSON) 

这可以解决您的问题。

相关问题