This is the written companion to my ToDo application video, one of the most-watched projects on my channel. It's a full web app, not just an API: a page that lists your tasks, forms to add and edit them, buttons to mark a task complete or delete it, and little pop-up notifications after every action. It uses Spring Boot 3, Spring MVC with JSP pages, Spring Data JPA and MySQL.
All code below is copied from the project on GitHub. I've also gone through the questions viewers posted under the video, so the errors people actually hit are covered at the end, with fixes.
How the app is put together
Requests flow through three layers, and each class has one job:
| Layer | Class / file | Its job |
|---|---|---|
| View | ViewToDoList.jsp, AddToDoItem.jsp, EditToDoItem.jsp | The HTML pages, styled with Bootstrap |
| Controller | ToDoController | Maps each URL to a method and picks which page to show |
| Service | ToDoService | The business rules: what "mark complete" or "save" actually means |
| Repository | IToDoRepo | Reads and writes the todo table; Spring Data JPA writes the SQL |
| Model | ToDo | One task: id, title, date and status |
This is the structure I use in real projects too. The controller never talks to the database directly; it asks the service, and the service asks the repository. That keeps each class small and easy to test.
Step 1: Project setup
Create a Spring Boot 3 project on start.spring.io with Java 17 and add Spring Web, Spring Data JPA, MySQL Driver and Spring Boot DevTools. Spring Boot doesn't render JSP pages out of the box, so add Tomcat Jasper (the JSP engine) and JSTL by hand. The full dependency list:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.6.0</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>1.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Step 2: Configure MySQL and JSP
spring.port = 8091 spring.mvc.view.prefix = /WEB-INF/jsp/ spring.mvc.view.suffix = .jsp spring.datasource.url = jdbc:mysql://localhost:3306/todo_app spring.datasource.username = root spring.datasource.password = root spring.jpa.hibernate.ddl-auto = update
The two spring.mvc.view lines tell Spring where your pages are. When a controller method returns "ViewToDoList", Spring adds the prefix and suffix and renders /WEB-INF/jsp/ViewToDoList.jsp. Notice the dot in .jsp: one viewer's error showed Spring looking for ViewToDoList/jsp, which is exactly what happens when the suffix is typed as /jsp.
spring.port, but Spring Boot has no property with that name, so it's silently ignored and the app starts on the default port 8080. If you want 8091, the correct property is server.port = 8091. Check the Tomcat started on port(s) line in your console to see which port you're on.ddl-auto = update creates the todo table for you, but not the database itself. Before the first run, create it in MySQL Workbench or the MySQL shell:
CREATE DATABASE todo_app;
If you skip this, or MySQL isn't running, or the username and password don't match your installation, startup fails. Change root/root to your own MySQL credentials.
Step 3: The model
package com.example.ToDoApp.model; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import jakarta.annotation.Nonnull; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table (name="todo") public class ToDo { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Nonnull private Long id; @Column @Nonnull private String title; @Column @Nonnull @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; @Column @Nonnull private String status; public ToDo() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
A plain entity with getters and setters, no Lombok this time. The interesting line is @DateTimeFormat(pattern = "yyyy-MM-dd"). An HTML date input sends dates as text like 2023-04-16, and this annotation tells Spring how to turn that text into a java.util.Date when the form is submitted. Without it, saving a task fails with a type conversion error. All imports are jakarta.*, because this project is on Spring Boot 3.
Step 4: The repository
package com.example.ToDoApp.repo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.ToDoApp.model.ToDo; @Repository public interface IToDoRepo extends JpaRepository<ToDo, Long>{ }
Extending JpaRepository<ToDo, Long> gives you findAll, findById, save and deleteById without writing a single query.
Step 5: The service
package com.example.ToDoApp.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.ToDoApp.model.ToDo; import com.example.ToDoApp.repo.IToDoRepo; @Service public class ToDoService { @Autowired IToDoRepo repo; public List<ToDo> getAllToDoItems() { ArrayList<ToDo> todoList = new ArrayList<>(); repo.findAll().forEach(todo -> todoList.add(todo)); return todoList; } public ToDo getToDoItemById(Long id) { return repo.findById(id).get(); } public boolean updateStatus(Long id) { ToDo todo = getToDoItemById(id); todo.setStatus("Completed"); return saveOrUpdateToDoItem(todo); } public boolean saveOrUpdateToDoItem(ToDo todo) { ToDo updatedObj = repo.save(todo); if (getToDoItemById(updatedObj.getId()) != null) { return true; } return false; } public boolean deleteToDoItem(Long id) { repo.deleteById(id); if (repo.findById(id).isEmpty()) { return true; } return false; } }
A few details are worth noticing:
saveOrUpdateToDoItemhandles both add and edit.save()inserts when the object has no id, and updates when it has one. That's why the edit form sends the id in a hidden field.updateStatusdoesn't need a form at all: it loads the task, sets the status toCompletedand saves it.getToDoItemByIdcalls.get()on theOptional. If someone opens/editToDoItem/999and that id doesn't exist, this throwsNoSuchElementExceptionand you get an error page. In a real app you'd useorElseThrow()with your own exception and show a friendly message.
Step 6: The controller
package com.example.ToDoApp.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.example.ToDoApp.model.ToDo; import com.example.ToDoApp.service.ToDoService; @Controller public class ToDoController { @Autowired private ToDoService service; @GetMapping({"/", "viewToDoList"}) public String viewAllToDoItems(Model model, @ModelAttribute("message") String message) { model.addAttribute("list", service.getAllToDoItems()); model.addAttribute("message", message); return "ViewToDoList"; } @GetMapping("/updateToDoStatus/{id}") public String updateToDoStatus(@PathVariable Long id, RedirectAttributes redirectAttributes) { if (service.updateStatus(id)) { redirectAttributes.addFlashAttribute("message", "Update Success"); return "redirect:/viewToDoList"; } redirectAttributes.addFlashAttribute("message", "Update Failure"); return "redirect:/viewToDoList"; } @GetMapping("/addToDoItem") public String addToDoItem(Model model) { model.addAttribute("todo", new ToDo()); return "AddToDoItem"; } @PostMapping("/saveToDoItem") public String saveToDoItem(ToDo todo, RedirectAttributes redirectAttributes) { if(service.saveOrUpdateToDoItem(todo)) { redirectAttributes.addFlashAttribute("message", "Save Success"); return "redirect:/viewToDoList"; } redirectAttributes.addFlashAttribute("message", "Save Failure"); return "redirect:/addToDoItem"; } @GetMapping("/editToDoItem/{id}") public String editToDoItem(@PathVariable Long id, Model model) { model.addAttribute("todo", service.getToDoItemById(id)); return "EditToDoItem"; } @PostMapping("/editSaveToDoItem") public String editSaveToDoItem(ToDo todo, RedirectAttributes redirectAttributes) { if(service.saveOrUpdateToDoItem(todo)) { redirectAttributes.addFlashAttribute("message", "Edit Success"); return "redirect:/viewToDoList"; } redirectAttributes.addFlashAttribute("message", "Edit Failure"); return "redirect:/editToDoItem/" + todo.getId(); } @GetMapping("/deleteToDoItem/{id}") public String deleteToDoItem(@PathVariable Long id, RedirectAttributes redirectAttributes) { if (service.deleteToDoItem(id)) { redirectAttributes.addFlashAttribute("message", "Delete Success"); return "redirect:/viewToDoList"; } redirectAttributes.addFlashAttribute("message", "Delete Failure"); return "redirect:/viewToDoList"; } }
It's @Controller, not @RestController: every method returns the name of a page instead of JSON. After an action that changes data, it returns redirect:/viewToDoList rather than rendering the page directly. That's the Post/Redirect/Get pattern, and it stops the browser from re-submitting the form if the user refreshes.
RedirectAttributes.addFlashAttribute is how the success message survives that redirect. A flash attribute is stored for exactly one request, so the list page receives message once and then it's gone. That's what drives the notifications.
Step 7: The pages
The list page
JSTL's <c:forEach> loops over the list attribute the controller put in the model, and ${todo.title} reads each property through its getter:
<form:form> <table class="table table-bordered"> <tr> <th>Id</th> <th>Title</th> <th>Date</th> <th>Status</th> <th>Mark Completed</th> <th>Edit</th> <th>Delete</th> </tr> <c:forEach var="todo" items="${list}"> <tr> <td>${todo.id}</td> <td>${todo.title}</td> <td>${todo.date}</td> <td>${todo.status}</td> <td><button type="button" class="btn btn-success"> <a href="/updateToDoStatus/${todo.id}">Mark Complete</a> </button></td> <td><button type="button" class="btn btn-primary"> <a href="/editToDoItem/${todo.id}">Edit</a> </button></td> <td><button type="button" class="btn btn-danger"> <a href="/deleteToDoItem/${todo.id}">Delete</a> </button></td> </tr> </c:forEach> </table> </form:form>
The add form
Spring's form tags bind each input to a field of the todo object. path="title" means "read and write todo.title", so when the form is posted, Spring builds a ToDo from the inputs and hands it to saveToDoItem:
<form:form action="/saveToDoItem" method="post" modelAttribute="todo"> <div class="row"> <div class="form-group col-md-12"> <label class="col-md-3" for="title">Title</label> <div class="col-md-6"> <form:input type="text" path="title" id="title" class="form-control input-sm" required="required" /> </div> </div> </div> <div class="row"> <div class="form-group col-md-12"> <label class="col-md-3" for="date">Date</label> <div class="col-md-6"> <form:input type="date" path="date" id="date" class="form-control input-sm" required="required" /> </div> </div> </div> <div class="row"> <div class="form-group col-md-12"> <label class="col-md-3" for="status">Status</label> <div class="col-md-6"> <form:input type="text" path="status" id="status" class="form-control input-sm" value="Incomplete" /> </div> </div> </div> <div class="row p-2"> <div class="col-md-2"> <button type="submit" value="Register" class="btn btn-success">Save</button> </div> </div> </form:form>
The edit page is the same form with two differences: it posts to /editSaveToDoItem, and it carries the id in <form:input path="id" type="hidden"/> so save() updates the existing row instead of inserting a new one.
The notifications
The pop-ups use toastr, loaded from a CDN. When the list page loads, a small script checks the flash message and shows the matching notification:
var msg = "${message}"; if (msg == "Save Success") { Command: toastr["success"]("Item added successfully!!") } else if (msg == "Delete Success") { Command: toastr["success"]("Item deleted successfully!!") } else if (msg == "Delete Failure") { Command: toastr["error"]("Some error occurred, couldn't delete item") } else if (msg == "Edit Success") { Command: toastr["success"]("Item updated successfully!!") }
Update Success after marking a task complete, but this script never checks for that message, so nothing shows. Add one more branch, else if (msg == "Update Success") { toastr["success"]("Item marked as completed!!") }, and it works. Also make sure the toastr CSS and JS tags load after jQuery, as they do here.Run it
- Start MySQL and run
CREATE DATABASE todo_app;once. - Put your MySQL username and password in
application.properties. - Run
ToDoAppApplicationand wait forTomcat started on port(s): 8080. - Open
http://localhost:8080/and click Add New ToDo Item.
Errors viewers hit most, and the fixes
| Error | Cause | Fix |
|---|---|---|
Failed to configure a DataSource | Spring can't find or reach your database | Check spring.datasource.*, the MySQL driver in pom.xml, and that MySQL is running |
Unknown database 'todo_app' | The database was never created | Run CREATE DATABASE todo_app; (or add ?createDatabaseIfNotExist=true to the URL) |
Access denied for user 'root' | Wrong MySQL credentials | Use your own username and password |
404 with No static resource ... ViewToDoList/jsp | Typo in the view suffix | spring.mvc.view.suffix = .jsp, with a dot |
| 404 on every page even though the JSP files exist | Tomcat Jasper (the JSP engine) is missing | Add tomcat-embed-jasper to pom.xml |
NullPointerException on repo or service | Class isn't a Spring bean, or created with new | Annotate it (@Service, @Controller) and keep every class under the main application's package |
| Whitelabel 500 error | An exception on the server | Scroll up in the console to the first Caused by: line; it names the real problem |
One more for Spring Boot 3 specifically: if the list page fails with NoClassDefFoundError: javax/servlet/jsp/tagext/TagSupport, your JSTL jar is the old javax version, which Tomcat 10 can't load. Replace the jstl:jstl:1.2 dependency with the Jakarta one:
<dependency> <groupId>jakarta.servlet.jsp.jstl</groupId> <artifactId>jakarta.servlet.jsp.jstl-api</artifactId> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>jakarta.servlet.jsp.jstl</artifactId> </dependency>
Spring Boot manages both versions, so no <version> is needed, and the taglib line in your JSP pages stays the same.
JSP or Thymeleaf?
A few viewers asked for this app in plain HTML instead of JSP. JSP still works, and it's worth knowing because plenty of older enterprise projects use it, but for new Spring Boot apps I'd use Thymeleaf: it works out of the box with no extra dependencies, and its templates are valid HTML you can open in a browser. My Ecommerce project is built with Thymeleaf from start to finish, and I compare the two in Is JSP Outdated? Thymeleaf vs JSP.
Source code and what to build next
The full project, including all three JSP pages, is on GitHub: github.com/sprashantofficial/ToDo-App. If you're stuck, comment on the video with the first error line from your console and I'll help.
If this is your first Spring Boot app, start one step earlier with the CRUD REST API in 30 minutes. For more full projects, see the Spring Boot Projects for Beginners playlist.
Comments
Post a Comment