LoginSignup
3
2

More than 5 years have passed since last update.

JerseyでリクエストエンテティJSONをBean ValidatorでvalidateしてエラーJSONレスポンスを返すチュートリアル

Last updated at Posted at 2016-08-07

参考文献

Bean Validationを依存関係に追加する

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-bean-validation</artifactId>
</dependency>

(versionはBOMで指定されたものを使うので書かない)

リクエストエンテティJSONにアノテーションで制約を付与する

class RequestBean {

    @NotNull
    private String propertyA;

    ...
}

リソースクラスのメソッドにアノテーションで制約を付与する

@Path("/")
class MyResourceClass {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void doSomething(@Valid @NonNull RequestBean user) {
        ...
    }
}

ConstraintViolationExceptionのExceptionMapperを実装する

@Provider
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
    @Override
    public Response toResponse(ConstraintViolationException ex) {
        return Response.status(Status.BAD_REQUEST)
            .entity(buildEntityFrom(ex))
            .type(MediaType.APPLICATION_JSON_TYPE)
            .build();
    }

ConstraintViolationの各パラメータには以下の値が格納されている:
* rootBean: リソースオブジェクト
* leafBean: リクエストエンテティBean
* propertyPath: <メソッド名>.arg0.<リクエストエンテティBeanのプロパティ名>
(リクエストエンテティ自体がnullの場合は <メソッド名>.arg0 )

(Jersey User Guide:18.7.1. ValidationErrorに記載されているように、
デフォルトでマッピングする機能もあるので、要件に合うのであればそれを使ってもよい)

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2