Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Number Validation

Validating number inputs is an important step to ensure that data received from user inputs is correct and consistent. Spring MVC provides support for validation through the Bean Validation API (typically the Hibernate Validator implementation).

Let's go through the steps of validating a number input in a Spring MVC application:

1. Adding Dependencies:

Firstly, add the necessary dependencies for validation in your pom.xml:

<!-- Spring Web MVC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.x.x.RELEASE</version>
</dependency>

<!-- Hibernate Validator (Bean Validation API) -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.x.x.Final</version>
</dependency>

2. Model/DTO:

Assuming you have a simple form that takes a number, let's validate it using annotations:

public class NumberForm {

    @NotNull(message = "Number cannot be empty")
    @Min(value = 1, message = "Number should not be less than 1")
    @Max(value = 100, message = "Number should not be greater than 100")
    private Integer number;

    // getters and setters
}

In the above class:

  • @NotNull: Ensures the number is not null.
  • @Min and @Max: Ensures the number is within the specified range.

3. Controller:

In the controller, use @Valid to trigger validation:

@Controller
@RequestMapping("/number")
public class NumberController {

    @GetMapping("/form")
    public String displayForm(NumberForm numberForm) {
        return "numberForm";
    }

    @PostMapping("/submit")
    public String submitForm(@Valid NumberForm numberForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "numberForm";
        }
        // process the form data
        return "successPage";
    }
}

Here, the BindingResult object contains the result of the validation. If there are errors, it can redirect back to the form.

4. View (JSP example):

Display the validation messages in your JSP:

<form action="/number/submit" method="post">
    <label for="number">Enter a number (1-100):</label>
    <input type="number" id="number" name="number" value="${numberForm.number}" />
    <form:errors path="number" cssClass="error" />
    <input type="submit" value="Submit" />
</form>

In the above JSP:

  • <form:errors> tag from Spring's form tag library is used to display validation errors related to the number field.

5. Configurations:

Ensure that the DispatcherServlet is configured to enable validation by adding the following bean in your configuration:

@Bean
public LocalValidatorFactoryBean validator() {
    return new LocalValidatorFactoryBean();
}

That's it! Now, when a user submits a number outside the range 1-100 or leaves the field empty, they will see the validation message. You can customize and expand upon these validations as required by your application's needs.

  1. Spring MVC Number Validation Example:

    • Description: This is a basic example showcasing number validation in a Spring MVC form.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Min(value = 1, message = "Please enter a positive number")
          private Integer quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  2. Number Validation in Spring MVC Forms:

    • Description: This example demonstrates how to perform number validation in a Spring MVC form.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Min(value = 1, message = "Please enter a positive number")
          private Integer quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  3. How to Validate Numeric Input in Spring MVC:

    • Description: This example illustrates how to validate numeric input in a Spring MVC form.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Digits(integer = 5, fraction = 0, message = "Please enter a valid numeric value")
          private Integer quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  4. Spring MVC Form Validation for Numeric Fields:

    • Description: This example showcases form validation for numeric fields in a Spring MVC application.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Digits(integer = 5, fraction = 2, message = "Please enter a valid numeric value with up to 2 decimal places")
          private BigDecimal price;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  5. Custom Number Validation in Spring MVC:

    • Description: This example demonstrates how to implement custom number validation in a Spring MVC application.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @CustomNumberValidator(message = "Please enter a valid custom numeric value")
          private Integer customNumber;
      
          // Getter and Setter
      }
      

      (Validator)

      public class CustomNumberValidator implements ConstraintValidator<CustomNumber, Integer> {
      
          @Override
          public boolean isValid(Integer value, ConstraintValidatorContext context) {
              // Custom validation logic
              return /* Validation result */;
          }
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  6. Using Annotations for Number Validation in Spring MVC:

    • Description: This example shows how to use annotations for number validation in a Spring MVC form.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @NumberFormat(style = Style.NUMBER)
          private Long quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  7. Handling Integer and Decimal Validation in Spring MVC:

    • Description: This example illustrates how to handle integer and decimal validation in a Spring MVC form.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @NumberFormat(style = Style.NUMBER)
          private Long quantity;
      
          @NotNull
          @NumberFormat(style = Style.CURRENCY)
          private BigDecimal price;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  8. Validating Numeric Ranges in Spring MVC:

    • Description: This example demonstrates how to validate numeric ranges in a Spring MVC form.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Min(value = 1, message = "Please enter a quantity greater than 0")
          @Max(value = 100, message = "Please enter a quantity less than or equal to 100")
          private Integer quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  9. Thymeleaf Number Validation in Spring MVC:

    • Description: This example showcases number validation using Thymeleaf in a Spring MVC application.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Min(value = 1, message = "Please enter a positive number")
          private Integer quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }
      
  10. Client-Side and Server-Side Number Validation in Spring MVC:

    • Description: This example demonstrates both client-side and server-side number validation in a Spring MVC application.

    • Code Snippet: (Entity/Model)

      public class Product {
      
          @NotNull
          @Min(value = 1, message = "Please enter a positive number")
          private Integer quantity;
      
          // Getter and Setter
      }
      

      (Controller)

      @Controller
      public class ProductController {
      
          @RequestMapping("/addProduct")
          public String addProduct(@Valid @ModelAttribute("product") Product product, BindingResult result) {
              if (result.hasErrors()) {
                  return "productForm";
              }
              // Process the product
              return "productConfirmation";
          }
      }