Q1. How would you implement a simple CRUD application in Spring MVC?
Create a controller with methods mapped to:
•
•
•
•
•
•
Use a service layer for business logic and a repository for data access.
Use form backing objects and validation.
•
/users (GET for list)•
/users/new (GET for form)•
/users (POST for create)•
/users/{id}/edit (GET for edit)•
/users/{id} (PUT for update)•
/users/{id} (DELETE for delete)Use a service layer for business logic and a repository for data access.
Use form backing objects and validation.
Q2. How do you handle form submission in Spring MVC?
Create a form backing object (POJO) and use
Example:
@ModelAttribute in controller method to bind form data.Example:
@PostMapping("/users")
public String createUser(@ModelAttribute User user) {
userService.save(user);
return "redirect:/users";
}
Q3. How do you perform validation in Spring MVC?
Use Bean Validation (JSR-380) annotations like
In controller, add
Example:
@NotNull, @Size on model fields.In controller, add
@Valid to the model attribute and a BindingResult parameter.Example:
@PostMapping("/users")
public String create(@Valid User user, BindingResult result) {
if(result.hasErrors()) return "userForm";
// save
}
Q4. How do you handle update and delete operations?
For update, use
For delete, use
In forms, you may need to use hidden
Spring's
@PutMapping (or @PostMapping with hidden method override).For delete, use
@DeleteMapping.In forms, you may need to use hidden
_method field if browser only supports GET and POST.Spring's
HiddenHttpMethodFilter enables this.Q5. What is the purpose of @ModelAttribute on a method?
When applied to a method,
It's useful for common data like reference data (e.g., list of countries).
The method is called before each handler method.
@ModelAttribute indicates that the method adds attributes to the model for all requests in that controller.It's useful for common data like reference data (e.g., list of countries).
The method is called before each handler method.
