The best practical guide to the Jersey Ext Bean Validation framework in the Java class library

Jersey Ext Bean Validation's Best Practice Guide introduce: Jersey is a popular Java Restful Web service framework, which provides powerful features to develop and deploy restful -style web services.Jersey Ext Bean Validation is an extended module of Jersey to integrate Java's Bean Validation framework to simplify the verification work on request parameters.This article will provide you with the best practical guide to Jersey Ext Bean Validation framework to help you use the framework correctly in actual development. 1. Import dependencies In the pom.xml file of the project, Jersey and Jersey Ext Bean Validation are added.The latest version can be found in the central warehouse of Maven. <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>${jersey.version}</version> </dependency> <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-bean-validation</artifactId> <version>${jersey.version}</version> </dependency> 2. Create resources Create a resource category marked with @path annotations, and use @valid annotation verification request parameters. @Path("/users") public class UserResource { @POST @Path("/register") public Response registerUser(@Valid User user) { // Treatment of user registration logic return Response.ok().build(); } } The User class in the above code is an ordinary Java Bean that uses the annotation of Bean Validation to define the verification rules.For example,@notnull annotations are used to verify parameters cannot be empty. 3. Configure value Configure Bean Validation to enable parameter verification.It can be implemented by adding configuration information to web.xml or using java code configuration. Use web.xml configuration: <context-param> <param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name> <param-value>true</param-value> </context-param> Use Java code configuration: public class ApplicationConfig extends ResourceConfig { public ApplicationConfig() { register(UserResource.class); property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); } } 4. Abnormal treatment In order to capture the abnormalities of the verification failure and return to meaningful errors, you can use the `ExceptionMapper` interface provided by Jersey to handle it. @Provider public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException ex) { ValidationErrorResponse errorResponse = new ValidationErrorResponse(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errorResponse.addError(violation.getPropertyPath().toString(), violation.getMessage()); } return Response.status(Response.Status.BAD_REQUEST).entity(errorResponse).build(); } } The ValidationerRerSponse in the above code is a custom error response class that is used to encapsulate the error information of failed to verify. 5. Writing unit test Write the unit test to verify whether the various verification rules work correctly.You can use Junit or other test frameworks to write test cases. public class UserResourceTest { @Rule public final ResourceTestRule resourceTestRule = ResourceTestRule.builder() .addResource(new UserResource()) .addProvider(new ConstraintViolationExceptionMapper()) .build(); @Test public void testRegisterUserWithInvalidData() { Response response = resourceTestRule.target("/users/register") .request() .post(Entity.json(new User())); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); ValidationErrorResponse errorResponse = response.readEntity(ValidationErrorResponse.class); assertNotNull(errorResponse); assertEquals(1, errorResponse.getErrors().size()); } } In the above code, UserResourceTest is a simple unit test class that can test whether the user registration interface can correctly return the error response when receiving the invalid data. Summarize: This article introduces the best practical guide to the Jersey Ext Bean Validation framework.Through correctly importing dependence, creating resources, configuring Validation, processing abnormalities, and writing unit tests, you can effectively use Bean Validation to check the request parameters when developing a web service using the RESTFUL style.I hope this article can help you.