Spring MVC CRUD
Now let us build something useful – a complete CRUD (Create, Read, Update, Delete) application for managing students. We will use Spring MVC with a simple in-memory list (database will come later).
Step 1: Create the Student Model
public class Student {
private int id;
private String name;
private String email;
private int age;
// constructors, getters, setters
}
Step 2: Create Controller with CRUD methods
@Controller
@RequestMapping("/students")
public class StudentController {
// In-memory list (instead of database)
private List students = new ArrayList<>();
private int nextId = 1;
// CREATE - Show form
@GetMapping("/new")
public String showNewForm(Model model) {
model.addAttribute("student", new Student());
return "student-form";
}
// CREATE - Save student
@PostMapping("/save")
public String saveStudent(@ModelAttribute Student student) {
student.setId(nextId++);
students.add(student);
return "redirect:/students";
}
// READ - List all students
@GetMapping
public String listStudents(Model model) {
model.addAttribute("students", students);
return "student-list";
}
// UPDATE - Show edit form
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable int id, Model model) {
Student student = students.stream().filter(s -> s.getId() == id).findFirst().orElse(null);
model.addAttribute("student", student);
return "student-form";
}
// UPDATE - Save edited student
@PostMapping("/update/{id}")
public String updateStudent(@PathVariable int id, @ModelAttribute Student updatedStudent) {
for (Student s : students) {
if (s.getId() == id) {
s.setName(updatedStudent.getName());
s.setEmail(updatedStudent.getEmail());
s.setAge(updatedStudent.getAge());
break;
}
}
return "redirect:/students";
}
// DELETE
@GetMapping("/delete/{id}")
public String deleteStudent(@PathVariable int id) {
students.removeIf(s -> s.getId() == id);
return "redirect:/students";
}
}
This controller handles all CRUD operations:
- Create – GET /students/new (show form), POST /students/save (save)
- Read – GET /students (list all)
- Update – GET /students/edit/{id} (show form), POST /students/update/{id} (save)
- Delete – GET /students/delete/{id} (delete)
Two Minute Drill
- CRUD = Create, Read, Update, Delete.
- Use @GetMapping for showing forms and @PostMapping for saving data.
- @PathVariable captures values from URL (like id).
- @ModelAttribute binds form data to Java object.
- Redirect prevents duplicate form submissions.
Need more clarification?
Drop us an email at career@quipoinfotech.com
