Skip to main content

Bean Validation (JSR 303) using Hibernate Validator in Spring Boot

Bean Validation
Bean validation has always been a tremendous effort in Java based Enterprise application development. Java Bean Validation (JSR 303) is the framework that defines how Java Beans should be validated. There are few validator APIs that support JSR 303. Hibernate validator is the most popular among them. It helps validate Java Beans using annotation and the beans can be validated at presentation layer, service and data access layer. Hibernate validator also offers custom validation, cross field validations. You can checkout the latest hibernate validator documentation for built-in validator annotations.

Assumption      : Spring Boot (1.5.6),  Hibernate Validator(5.4.1.Final), Maven Projects

Integrating Spring Boot & Hibernate Validator
Spring Boot offers built-in starter dependency management for most of the frameworks and APIs available in Java Application Development. It has support for bean validation using hibernate validator API. The discussion focuses on how to validate presentation layer by Hibernate Validator using Spring Boot.

Step 1: Spring Boot has a starter validation that inherits hibernate validator. All we need to do is to add this starter dependency in pom.xml for spring boot application.

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

As soon as we add this dependency, Spring Boot will download and be aware of hibernate validator and we can use it to validate the beans in presentation layer which is Spring MVC in our case.

Step 2: Enable constraint annotations on Java Beans. Below example shows how to add annotations to validate the constraint on the fields. The naming of the message will be always ConstraintName.BeanName.PropertyName.

 public class EmployeeForm implements Serializable {

  private String id;

  @Size(min = 1, max = 50, message = "{Size.employeeForm.firstName}")
  private String firstName;

  @Size(min = 1, max = 50, message = "{Size.employeeForm.lastName}")
  private String lastName;

  @NotBlank(message = "{NotBlank.employeeForm.dob}")
  private String dob;

  @NotBlank(message = "{NotBlank.employeeForm.gender}")
  private String gender = Gender.MALE.getCode();

  @NotBlank(message = "{NotBlank.employeeForm.email}")
  @Email(message = "{Email.employeeForm.email}")
  private String email;
  
 }

Step 3: To validate the form (Java Bean) in presentation layer (Spring MVC), we have to add @Valid annotation in the controller mapping like below. That will do all the tricks to validate the field constraints. Pretty simple. isn't it?

    @PostMapping(value = "/employees/create.mk")
    public String createEmployees(@Valid @ModelAttribute("newEmployeeForm") 
                  EmployeeForm employeeForm, BindingResult result, ModelMap model) {
        if (result.hasErrors()) {        
            model.addAttribute("employeeFormError", Boolean.TRUE);
            return ADD_EMPLOYEES;
        }      
        return "redirect:/employees/view.mk";
    }

Hibernate Validator has only limited built-in constraints but it has extensibility. We can create our own constraints to suit the needs. 

Comments

  1. This information is meaningful and magnificent which you have shared here. I am impressed by the details that you have shared in this post and It reveals how nicely you understand this subject. I would like to thanks for sharing this article here. Custom Website Development Services.

    ReplyDelete
  2. If you continue enjoying in} past that, find a way to|you presumably can} amp up your on line casino bankroll with 4 BTC extra throughout your subsequent three deposits, totaling a formidable 5 BTC welcome package. Bitstarz additionally be|can be} the one on line casino on this listing the place find a way to|you presumably can} enjoy unique titles. That mentioned, our high game 카지노사이트 here was Master of Starz, which additionally be|can be} the biggest progressive jackpot find a way to|you presumably can} enjoy here.

    ReplyDelete

Post a Comment

Popular posts from this blog

CSRF enabled Ajax requests using Spring Security

Many of you who have worked on Spring Security might be aware of the fact that Spring Security protects applications from Cross Site Request Forgery using _csrf tokens in the request sent to the web server. You can find a detailed understanding in the Spring documentation page . The objective of this post is to explain how to send _csrf tokens in the Ajax requests when we protect our application URL and application access using spring security. How to get CSRF tokens While we submit a form using an application that is protected with Spring Security, the form gets a default hidden parameter in the form body when using <form:form> element. The param contains the _csrf tokens to authenticate the requests in the server. In case we use other ways to create forms, we have to manually include a hidden parameter that contains name as ${_csrf.parameterName} and  value as ${_csrf.token} . For example, <input type= "hidden" name= "${_csrf.parameterName}"

A wonderful technique to reduce website development cost

Websites - Good way to get online presence Websites are very vital to get online presence of any business nowadays. Websites are categorized into two different types. First one is Static Website and second one is Dynamic Website, normally known as web applications. Static websites are most widely used for any business since they help to bring up the online presence more easily and quickly. Depending on the content and features, static websites cost around $300-$700 . It includes web design and development. Apart from that, the business has to spend for hosting space and domain name for the website. Cloud based development is now more prevalent. Building a website and running it will be very easy and cheap using these cloud infrastructure. But the difficulty facing the development of static websites still looms high as it does not matter who provides the infrastructure. The development cost is still same. Technology - LAMP Static websites are developed using HTML and PHP mostly

Disable Datasource Auto Configuration in Spring Boot

Today morning, We had an interesting situation. Our spring boot application which is configured to run on MySQL needs to be run on a system which does not have MySQL database installed. But we had to develop few UI modules alone. So we decided to go ahead but how do we disable MySQL database auto-configuration? Here is what we did . Spring Boot is an interesting framework that helps auto configure everything for you. In case you need to override any of the auto-configuration, all you need to do is to simply customize it. The auto-configuration backs away. In this typical scenario, we dont want to customize the auto-configuration, rather we want to disable it temporarily until we complete our UI modules. As soon as the system is ready or we find alternate systems, we can run the Application with full-blown schema. OK. so how did we disable the database auto configuration? We are using Spring Boot with JPA, Hibernate and FlywayDB migration tool. If this is going to be your boot