2018年8月22日 星期三

[Java] Jersey 使用 javax.validation.constraints.*

常常會需要使用 @NotNull、@NotBlank,但是不會運作,參考官網之後的做法:

// build.gradle
dependencies {
    compile (
        'org.glassfish.jersey.ext:jersey-bean-validation:2.27',
        'org.hibernate:hibernate-validator:6.0.12.Final',
        'javax.el:javax.el-api:3.0.0',
    )
}

設定回傳訊息。

    @GET
    @Path("/hello")
    public Response getMessage(@NotBlank(message = "empty name") @QueryParam("name") String name) { ... }

開啟變數,改成自己處理錯誤,不使用 Servlet server 回傳訊息。

import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;

@ApplicationPath("/")
public class WebApplication extends ResourceConfig {

    public WebApplication() {
        ...
        // ValidationExceptionMapper catchable
        property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    }
}

import java.util.List;
import java.util.stream.Collectors;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class ValidationExceptionMapper implements ExceptionMapper {

    @Override
    public Response toResponse(ValidationException e) {
        List msgs = null;
        if (e instanceof ConstraintViolationException) {
            List msgs = ((ConstraintViolationException) e).getConstraintViolations()
                    .stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.toList());
        } else {
            ...
        }

        return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(msgs).build();
    }

}

參考資料:

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

最近系統需要使用 Netty4,所以把衝突的 Netty3 拆掉,然後就出現了例外。 pom.xml <dependency> <groupId>com.ning</groupId> <artifactId>as...