Q1. How do you create a form in Spring MVC?
Use JSP with Spring form tags (e.g.,
The form backing object is exposed as a model attribute.
Example in JSP:
form:form, form:input) or Thymeleaf.The form backing object is exposed as a model attribute.
Example in JSP:
<form:form modelAttribute="user" method="post">
<form:input path="name"/>
<form:errors path="name"/>
</form:form>
Q2. What is BindingResult?
It must come immediately after the model attribute annotated with
It allows you to check for errors and access them in the view.
BindingResult holds the result of data binding and validation.It must come immediately after the model attribute annotated with
@Valid.It allows you to check for errors and access them in the view.
Q3. How do you display validation errors in the view?
Using
The errors are automatically added to the model by
You can iterate over them or show field-specific errors.
form:errors tag in JSP or Thymeleaf's th:errors.The errors are automatically added to the model by
BindingResult.You can iterate over them or show field-specific errors.
Q4. How do you perform custom validation?
Implement
For cross-field validation, you can use class-level constraints.
Example:
Validator interface or create custom annotation with ConstraintValidator.For cross-field validation, you can use class-level constraints.
Example:
@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
public @interface PasswordMatches { ... }
Q5. What is the role of @InitBinder?
It runs before the handler method.
@InitBinder methods in controllers allow you to configure data binding, such as setting allowed/disallowed fields, registering custom property editors, or adding validators.It runs before the handler method.
