Câu hỏi phỏng vấn Spring
Câu hỏi

How to validate form data in Spring Web MVC Framework?

Câu trả lời

To validate form data in Spring Web MVC Framework, you can use the following approaches:

Bean Validation API

Spring MVC supports the Bean Validation API (JSR-303 and JSR-349) for validating form objects. This API allows you to annotate your model attributes with built-in constraints such as @NotNull, @Size, @Min, @Max, and @Pattern to enforce validation rules. You can also create custom constraints if the standard ones do not fit your needs[2][3][6][7].

Using @Valid or @Validated Annotations

When a form is submitted, you can use the @Valid or @Validated annotations on a model attribute in your controller method to trigger the validation process. The @Valid annotation is part of the standard Bean Validation API, while @Validated is a Spring-specific variant that provides additional features such as validation groups[1][5][9].

Handling Validation Errors

To handle validation errors, you can include a BindingResult or Errors object immediately after the model attribute in the method signature. If validation errors are present, they will be added to the BindingResult object, and you can then check for these errors and return the form view with error messages[1][3][4][6][7].

Custom Validators

If you need more complex validation logic, you can implement the org.springframework.validation.Validator interface and define your own validation logic. You can then register this custom validator with a controller using the @InitBinder annotation[4][10].

Error Messages and Internationalization

You can define error messages directly in the validation annotations or externalize them to a properties file for internationalization purposes. Spring can use these messages to display user-friendly error messages on the form[2][6][8].

Example

Here's a simplified example of how you might validate a form in a Spring MVC controller:

...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is default scope of bean in Spring framework?

expert

What are some of the valid return types of a controller method?

middle

Can we send an Object as the response of Controller handler method?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào