Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

spring boot validation example with annotation

pom.xml

4.0.0org.springframework.boot
		spring-boot-starter-parent
		2.2.6.RELEASEcom.candidjava.spring.boot
	validation
	0.0.1-SNAPSHOTvalidationDemo project for Spring Boot1.8org.springframework.boot
			spring-boot-starter-validation
		org.springframework.boot
			spring-boot-starter-web
		org.springframework.boot
				spring-boot-maven-plugin
			

CommunicationType.java

package com.candidjava.springboot.validators;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({
 ElementType.FIELD
})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CommunicationTypeValidator.class)
@Documented
public @interface CommunicationType {
 String message() default "Communication preference must be email or mobile.";

 Class>[] groups() default {};

 Class [] payload() default {};
}

CommunicationTypeValidator.java

package com.candidjava.springboot.validators;

import java.util.Arrays;
import java.util.List;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CommunicationTypeValidator implements ConstraintValidator {

 @Override
 public boolean isValid(String value, ConstraintValidatorContext context) {
  final List commType = Arrays.asList("email", "mobile");
  return commType.contains(value);
 }

}

Student.java

package com.candidjava.springboot.models;

import javax.validation.constraints.NotEmpty;

import com.candidjava.springboot.validators.CommunicationType;

public class Student {
 private String id;
 @NotEmpty(message = "First name is required")
 private String name;
 private String age;
 @NotEmpty(message = "email is required")
 private String email;
 @NotEmpty(message = "mobile number is required")
 private String mobile;
 @NotEmpty(message = "Communication Type preference is required")
 @CommunicationType
 private String communicationType;

 public Student(String id, String name, String age, String email, String mobile, String communicationType) {
  this.id = id;
  this.name = name;
  this.age = age;
  this.email = email;
  this.mobile = mobile;
  this.communicationType = communicationType;
 }

 public String getCommunicationType() {
  return communicationType;
 }

 public void setCommunicationType(String communicationType) {
  this.communicationType = communicationType;
 }

 public String getName() {
  return name;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getMobile() {
  return mobile;
 }

 public void setMobile(String mobile) {
  this.mobile = mobile;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

}

StudentService.java

package com.candidjava.springboot.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import com.candidjava.springboot.models.Student;
import com.candidjava.springboot.service.StudentService;

@Service
public class StudentService {

 private List studentList = new ArrayList (Arrays.asList(

  new Student("1", "ram", "20", "[email protected]", "9876543210", "email"),
  new Student("2", "arun", "21", "[email protected]", "987654321", "mobile"),
  new Student("3", "karthick", "22", "[email protected]", "987654322", "email")

 ));

 public void createStudent(Student student) {
  studentList.add(student);
 }

 public List getAllStudents() {
  return studentList;

 }

 public Student getStudentById(String id) {
  return studentList.stream().filter(student -> student.getId().equals(id)).findFirst().get();

 }

 public void updateStudent(String id, Student student) {
  int counter = 0;
  for (Student eachStudent: studentList) {
   if (eachStudent.getId().equals(id)) {
    studentList.set(counter, student);
   }
   counter++;
  }
 }

 public void deleteStudentById(String id) {
  studentList.removeIf(student -> student.getId().equals(id));
 }

}

StudentController.java

package com.candidjava.springboot.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.candidjava.springboot.models.Student;
import com.candidjava.springboot.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {
 @Autowired
 StudentService service;

 @PostMapping("/create")
 public void create(@Valid @RequestBody Student student) {
  service.createStudent(student);
 }

 @GetMapping("/getAll")
 public List get() {
  return service.getAllStudents();
 }

 @GetMapping("/get/{id}")
 public Student getById(@PathVariable("id") String id) {
  return service.getStudentById(id);
 }

 @PutMapping("/update/{id}")
 public void update(@PathVariable("id") String id, @Valid @RequestBody Student student) {
  service.updateStudent(id, student);
 }

 @DeleteMapping("/delete/{id}")
 public void deleteById(@PathVariable("id") String id) {
  this.service.deleteStudentById(id);
 }

 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ExceptionHandler(MethodArgumentNotValidException.class)
 public Map handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
  Map errors = new HashMap();
  ex.getBindingResult().getFieldErrors()
   .forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));
  return errors;
 }
}

Application.java

package com.candidjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }

}


This post first appeared on Core Java,Servlet,Jsp,Struts,Hibernate,Spring Fram, please read the originial post: here

Share the post

spring boot validation example with annotation

×

Subscribe to Core Java,servlet,jsp,struts,hibernate,spring Fram

Get updates delivered right to your inbox!

Thank you for your subscription

×