Jersey 2.13 + Bean验证

时间:2015-10-01 13:53:47

标签: spring bean-validation jersey-2.0

我正在使用gradle和以下库:

ext.library['jersey'] = "org.glassfish.jersey:project:2.13"
ext.library['jersey_jettison'] = "org.glassfish.jersey.media:jersey-media-json-jettison:2.13"
ext.library['jersey_jackson'] = "org.glassfish.jersey.media:jersey-media-json-jackson1:2.13"
ext.library['jersey_spring'] = "org.glassfish.jersey.ext:jersey-spring3:2.13"
ext.library['jersey_bean_validation'] = "org.glassfish.jersey.ext:jersey-bean-validation:2.13"

我创建了bean验证结构,但它根本没有验证。没有错误消息,没有。这是我创建的结构:

DTO

public class MergeSchedulesDto {

@NotNull(message = "validation.invalid.mergeFrom")
private Long mergeFrom;

@NotNull(message = "validation.invalid.mergeTo")
@NotEmpty(message = "validation.invalid.mergeTo")
private List<Long> mergeTo;

服务

@Path("merge")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
public Response merge(@Valid MergeSchedulesDto dto, @QueryParam("units") List<Long> units) {

配置

public class ApplicationJAXRS extends Application {

    public ApplicationJAXRS() {
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<>();
        properties
                .put("jersey.config.server.provider.packages",
                        "com.sifionsolution.sig.academic.resource.service,com.sifionsolution.sig.integration.resource.filter,com.sifionsolution.sig.academic.param.converter,com.sifionsolution.sig.datatables.resource.service,com.sifionsolution.sig.datatables.converter");

        return properties;
    }

    @Override
    public Set<Object> getSingletons() {
        Set<Object> singletons = new HashSet<>();

        singletons.add(new Jackson1Feature());
        singletons.add(new ValidationExceptionMapper());

        return singletons;
    }
}

编辑我忘记了提供商:

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        return Response.status(BAD_REQUEST).entity(exception.getMessage()).build();
    }

}

编辑2:我删除了JUnit测试,因为我没有使用Jersey Test Framework进行测试。 这里的问题是ValidationExceptionMapper没有被调用。

1 个答案:

答案 0 :(得分:0)

将“@Valid”放入您的内容中,如下所示:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response insert(@Valid T obj) throws Exception{
...
}

这可以在这里工作。