Jersey Bean Validation Example

Jersey Bean Validation Example explains about Jersey bean valiation both input validations and service layer validations

JAX-RS is Java API for RESTful Webservices which is very rely upon Representational State Transfer model, you can view JAX-RS specification 

JAX-RS uses annotations for simplifying the development efforts.

Now a days more & more deployment is going based on restful services compare to WSDL Webservices, due to the weights towards the simplicity of configuration

Bean Validation is a process of verifying that some data obeys one or more pre-defined constraints. The Bean Validation specification supports the use of constraint annotations as a way of declaratively validating beans, method parameters and method returned values. Below post describes support for Bean Validation in Jersey in terms of the needed dependencies, configuration, registration and usage

Reference -> https://jersey.java.net/documentation/latest/bean-validation.html

You can see the below example, which is demonstrating How to do bean validations using jersey 2

Required Libraries

You need to download

  1. JDK 7
  2. Eclipse 4.2
  3. Jersey 2.19
  4. Tomcat 8

Following jar must be in classpath

  1. classmate-0.8.0.jar
  2. hibernate-validator-5.1.2.Final.jar
  3. hk2-api-2.4.0-b06.jar
  4. hk2-locator-2.4.0-b06.jar
  5. hk2-utils-2.4.0-b06.jar
  6. jackson-annotations-2.4.6.jar
  7. jackson-core-2.4.6.jar
  8. jackson-databind-2.4.6.jar
  9. jackson-jaxrs-base-2.3.2.jar
  10. jackson-jaxrs-json-provider-2.3.2.jar
  11. jackson-module-jaxb-annotations-2.3.2.jar
  12. javassist-3.18.1-GA.jar
  13. javax.annotation-api-1.2.jar
  14. javax.inject-2.4.0-b25.jar
  15. javax.ws.rs-api-2.0.1.jar
  16. jboss-logging-3.1.1.GA.jar
  17. jersey-bean-validation-2.19.jar
  18. jersey-client.jar
  19. jersey-common.jar
  20. jersey-container-servlet-core.jar
  21. jersey-container-servlet.jar
  22. jersey-guava-2.19.jar
  23. jersey-media-json-jackson-2.14.jar
  24. jersey-server.jar
  25. validation-api-1.1.0.Final.jar

Jersey Bean Validation Example

I am creating a sample restful service project that pass Student id and return the name of student. Here Jersey bean validation is using to check whether the student id is blank and also return if student is not exist. The service is using simple POJO (Plain Old Java Object) bean.

Firstly create a Dynamic Web Project (File->New->Dynamic Web Project) named "Jersey2Validation" according to following screenshot

Create Jersey Project Jersey Bean Validation Example

Create a StudentID validator

Here StudentID interface is used for defining the logic for this service, inside isValid() method we are checking the conditions

package com.student.validator;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = StudentID.StudentIDValidator.class)
public @interface StudentID {
String message() default "StudentID does not exist";

    Class<?>
[] groups() default {};

    Class<?
extends Payload>[] payload() default {};


public class StudentIDValidator implements ConstraintValidator<StudentID, String> {

@Override
public void initialize(final StudentID studentID) {
        }

@Override
public boolean isValid(final String studentID, ConstraintValidatorContext ctx) {
return studentID != null;
}
    }

}

Create a Controller

Inside StudentController, we are validating the student id and it should not be blank. if student id is blank it will return the message using Hibernate validator. Service also returns the error message if student is not exist corresponding to the student id

Here we are using one example showing with GET method & another with POST method

GET---> Calling this method will not result any changes to the server

POST---> Calling this method will result changes to the server, This have more secure than GET method

package com.student.controller;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.hibernate.validator.constraints.NotBlank;

import com.student.validator.StudentID;

@Path("Services")
public class StudentController {


@POST
    @Path
("/changeName")
@StudentID
    @Produces
(MediaType.APPLICATION_JSON)
public String getStudentID(@NotBlank(message = "Search string cannot be empty") final String id) {
return findStudentByID(id);

}

// mocking the data, you need to retrieve from database
private String findStudentByID(String id) {
if ("1".equals(id)) {
return "Rockey";
} else {
return null;
}
    }

}

@Consumes annotation specifies, the request is coming from the client

you can specify the Mime type as @Consumes("application/xml"), if the request is in xml format

@Produces annotation specifies, the response is going to the client

you can specify the Mime type as @Produces ("application/xml"), if the response need to be in xml format

Create ApplicationConfig

Here we register the StudentController class, so that jersey will invoke properly

package com.config;

import org.glassfish.jersey.server.ResourceConfig;

import com.controller.StudentController;


public class ApplicationConfig extends ResourceConfig {

public ApplicationConfig() {
register(StudentController.class);
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>Jersey2Validation</display-name>
	<servlet>
		<servlet-name>jersey</servlet-name>
		<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
		<init-param>
			<param-name>javax.ws.rs.Application</param-name>
			<param-value>com.config.ApplicationConfig</param-value>
		</init-param>
		<init-param>
			<param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>jersey</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

Publishing Jersey 2 Restful Service

Run Jersey Restful On Tomcat

Jersey Bean Validation Output When Student ID Blank

Jersey Bean Validation

Jersey Bean Validation Output When Valid Student ID

Jersey Bean Validation

Jersey Bean Validation Output When Student Not Exists

Here there is no student exists corresponding to studentid 2

Jersey Bean Validation

Note

you can also see Restful Client in order to run this restful service









Your email address will not be published. Required fields are marked *