Spring MVC
Spring MVC is the web framework inside Spring that maps HTTP requests to Java methods and turns their results into HTML pages or JSON. It follows the Model-View-Controller pattern: a controller method handles the request, fills a model with data, and a view template renders that data as HTML. Spring MVC replaces hand-written servlets with small annotated methods, while still running on a servlet container such as Tomcat.
This lesson builds server-rendered pages for a course website with Spring Boot 4.1, Spring MVC 7 and the Thymeleaf template engine: course lists, detail pages, a validated enquiry form and friendly error pages.
How a Spring MVC Request Is Processed
| Step | Component | What happens |
|---|---|---|
| 1 | DispatcherServlet | The single front servlet receives every request |
| 2 | Handler mapping | Finds the controller method whose @GetMapping/@PostMapping matches the URL |
| 3 | Controller | Runs your method; it reads parameters and fills the Model |
| 4 | View name | The method returns a name such as "courses" |
| 5 | View resolver | Turns the name into templates/courses.html |
| 6 | Thymeleaf | Renders the template with the model data into HTML |
How it works:
- In the Java Web Application lesson each servlet had its own URL. In Spring MVC, one
DispatcherServletreceives everything and routes requests to plain methods. - A
@Controllerreturns a view name and produces HTML. A@RestController(used in the Spring Boot tutorial) returns data that is written as JSON.
Add Spring MVC and Thymeleaf to Spring Boot
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
How it works:
- With the Thymeleaf starter present, Spring Boot auto-configures a view resolver that looks for
src/main/resources/templates/<viewName>.html. - The validation starter adds Hibernate Validator, which checks annotations such as
@NotBlankon form objects. - During development, add
spring.thymeleaf.cache=falsetoapplication.propertiesso template edits appear without a restart.
Your First Spring MVC Controller and Template
package com.gocourse.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("platform", "GOCOURSE");
model.addAttribute("courseCount", 3);
return "home"; // -> src/main/resources/templates/home.html
}
}
<!-- src/main/resources/templates/home.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>CourseHub</title></head>
<body>
<h1 th:text="'Welcome to ' + ${platform}">Welcome</h1>
<p>We offer <span th:text="${courseCount}">0</span> courses.</p>
<a th:href="@{/courses}">Browse courses</a>
</body>
</html>
curl -s http://localhost:8080/
Output:
<!DOCTYPE html>
<html>
<head><title>CourseHub</title></head>
<body>
<h1>Welcome to GOCOURSE</h1>
<p>We offer <span>3</span> courses.</p>
<a href="/courses">Browse courses</a>
</body>
</html>
How it works:
- The
Modelis a map of values for the view.addAttribute("platform", ...)makes${platform}available in the template. th:textreplaces the tag's content, so the placeholder textWelcomeis only seen when the file is opened directly in a browser. Thymeleaf templates stay valid HTML that designers can preview.@{/courses}builds a link that includes the application's context path automatically.
Request Mapping and Method Parameters
| Annotation | Matches |
|---|---|
@GetMapping("/courses") | GET /courses |
@PostMapping("/enquiry") | POST /enquiry |
@PutMapping, @PatchMapping, @DeleteMapping | Other HTTP methods (mainly for REST APIs) |
@RequestMapping("/admin") on the class | A common prefix for every method in the controller |
| Parameter annotation | Reads | Example URL / source |
|---|---|---|
@RequestParam | Query string or form field | /courses?category=web |
@PathVariable | Part of the path | /courses/java |
@ModelAttribute | Many form fields into one object | HTML form POST |
@RequestHeader | An HTTP header | Accept-Language |
@CookieValue | A cookie | theme=dark |
@RequestBody | The whole body (JSON) | REST APIs |
How it works:
- Spring converts text to the parameter type, so
@RequestParam int pagereceives a number. A value that cannot be converted gives400 Bad Request. @RequestParamis required by default. Userequired = falseordefaultValue = "..."for optional values.
List and Detail Pages With @RequestParam and @PathVariable
A small in-memory catalog serves the pages. In a real application it would use the repository from the Spring Data JPA lesson.
package com.gocourse.web;
public record Course(String code, String title, String category, int feeInr, int seatsLeft) {}
package com.gocourse.web;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
@Service
public class CourseCatalog {
private final List<Course> courses = List.of(
new Course("java", "Java Programming", "backend", 4999, 12),
new Course("spring", "Spring Boot", "backend", 5999, 0),
new Course("html", "HTML and CSS", "web", 1999, 30));
public List<Course> find(String category, String sort) {
Comparator<Course> order = "fee".equals(sort)
? Comparator.comparingInt(Course::feeInr)
: Comparator.comparing(Course::title);
return courses.stream()
.filter(course -> category == null || course.category().equals(category))
.sorted(order)
.toList();
}
public Optional<Course> byCode(String code) {
return courses.stream().filter(course -> course.code().equals(code)).findFirst();
}
}
package com.gocourse.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/courses")
public class CourseController {
private final CourseCatalog catalog;
public CourseController(CourseCatalog catalog) {
this.catalog = catalog;
}
@GetMapping
public String list(@RequestParam(required = false) String category,
@RequestParam(defaultValue = "title") String sort,
Model model) {
model.addAttribute("courses", catalog.find(category, sort));
model.addAttribute("category", category);
return "courses";
}
@GetMapping("/{code}")
public String detail(@PathVariable String code, Model model) {
Course course = catalog.byCode(code).orElseThrow(() -> new CourseNotFoundException(code));
model.addAttribute("course", course);
return "course-detail";
}
}
<!-- templates/courses.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Courses</title></head>
<body>
<h1 th:text="${category == null} ? 'All courses' : 'Category: ' + ${category}">Courses</h1>
<ul>
<li th:each="course : ${courses}">
<a th:href="@{/courses/{code}(code=${course.code})}" th:text="${course.title}">Title</a>
- Rs. <span th:text="${course.feeInr}">0</span>
<strong th:if="${course.seatsLeft == 0}">(Full)</strong>
</li>
</ul>
<p th:if="${courses.isEmpty()}">No courses in this category yet.</p>
</body>
</html>
curl -s "http://localhost:8080/courses?category=backend&sort=fee"
Output (whitespace trimmed):
<h1>Category: backend</h1>
<ul>
<li><a href="/courses/java">Java Programming</a> - Rs. <span>4999</span></li>
<li><a href="/courses/spring">Spring Boot</a> - Rs. <span>5999</span> <strong>(Full)</strong></li>
</ul>
How it works:
categoryis optional, so/coursesshows everything while?category=backendfilters.sortfalls back to"title"when it is missing.th:eachrepeats the<li>for every course, andth:ifremoves the(Full)tag unless no seats are left.@{/courses/{code}(code=${course.code})}fills the{code}placeholder and URL-encodes it, which is safer than building links with string concatenation.- Thymeleaf reads record components such as
${course.title}directly through their accessor methods.
Handle Forms With @ModelAttribute and Validation
Forms bind many fields into one object. Validation annotations describe the rules once, and Spring checks them for you.
package com.gocourse.web;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class EnquiryForm {
@NotBlank(message = "Please enter your name")
private String name;
@NotBlank(message = "Please enter your email")
@Email(message = "Please enter a valid email address")
private String email;
@NotBlank(message = "Please choose a course")
private String courseCode;
@Size(min = 10, max = 300, message = "Message must be 10 to 300 characters")
private String message;
// Getters and setters are required for form binding
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getCourseCode() { return courseCode; }
public void setCourseCode(String courseCode) { this.courseCode = courseCode; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
}
package com.gocourse.web;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class SimpleEnquiryController {
@GetMapping("/enquiry")
public String showForm(Model model) {
model.addAttribute("enquiryForm", new EnquiryForm()); // empty form object
return "enquiry";
}
@PostMapping("/enquiry")
public String submit(@Valid @ModelAttribute EnquiryForm enquiryForm,
BindingResult result,
RedirectAttributes redirect) {
if (result.hasErrors()) {
return "enquiry"; // show the same form again, with error messages
}
redirect.addFlashAttribute("notice", "Thanks " + enquiryForm.getName() + ", we will email you soon.");
return "redirect:/enquiry/thanks";
}
@GetMapping("/enquiry/thanks")
public String thanks() {
return "thanks";
}
}
<!-- templates/enquiry.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Course Enquiry</title></head>
<body>
<h1>Ask about a course</h1>
<form th:action="@{/enquiry}" th:object="${enquiryForm}" method="post">
<label>Name <input th:field="*{name}"></label>
<span class="error" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
<label>Email <input th:field="*{email}"></label>
<span class="error" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
<label>Course code <input th:field="*{courseCode}"></label>
<span class="error" th:if="${#fields.hasErrors('courseCode')}" th:errors="*{courseCode}"></span>
<label>Message <textarea th:field="*{message}"></textarea></label>
<span class="error" th:if="${#fields.hasErrors('message')}" th:errors="*{message}"></span>
<button>Send</button>
</form>
</body>
</html>
<!-- templates/thanks.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body><p th:text="${notice} ?: 'Thank you!'">Thank you!</p></body>
</html>
# Invalid submission: blank name, bad email, short message
curl -s -X POST http://localhost:8080/enquiry \
-d "name=&email=asha-at-mail&courseCode=java&message=Hi" | grep error
Output:
<span class="error">Please enter your name</span>
<span class="error">Please enter a valid email address</span>
<span class="error">Message must be 10 to 300 characters</span>
# Valid submission, following the redirect with a cookie jar
curl -s -L -c jar.txt -b jar.txt -X POST http://localhost:8080/enquiry \
-d "name=Asha&email=asha@example.com&courseCode=java&message=Is there a weekend batch?"
Output:
<!DOCTYPE html>
<html>
<body><p>Thanks Asha, we will email you soon.</p></body>
</html>
How it works:
th:objectbinds the form toenquiryForm, andth:field="*{name}"sets the input'sname,idand currentvalue. After a failed submission, the user's typing is still in the fields.@Validruns the validation annotations. TheBindingResultmust come directly after the validated parameter; otherwise Spring throws an exception instead of letting you show the errors.th:errorsprints the message from the annotation, such asPlease enter your name.- On success the controller returns
redirect:/enquiry/thanks(Post/Redirect/Get). A flash attribute survives exactly one redirect, so the thank-you text appears once and disappears on refresh. It is stored in the session, which is why curl needs a cookie jar.
Return JSON From a @Controller With @ResponseBody
A page controller can still offer a small JSON endpoint, for example for JavaScript on the page.
package com.gocourse.web;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SeatController {
private final CourseCatalog catalog;
public SeatController(CourseCatalog catalog) {
this.catalog = catalog;
}
@GetMapping("/courses/{code}/seats")
@ResponseBody // write the return value as JSON instead of resolving a view
public Map<String, Object> seats(@PathVariable String code) {
Course course = catalog.byCode(code).orElseThrow(() -> new CourseNotFoundException(code));
return Map.of("code", course.code(), "seatsLeft", course.seatsLeft(), "open", course.seatsLeft() > 0);
}
}
curl -s http://localhost:8080/courses/spring/seats
Output (key order may vary):
{"code":"spring","seatsLeft":0,"open":false}
How it works:
@ResponseBodytells Spring MVC to skip the view resolver and convert the return value with Jackson.@RestControlleris simply@Controllerplus@ResponseBodyon every method./courses/{code}/seatsdoes not clash with/courses/{code}because Spring picks the most specific matching pattern.
Show Friendly Error Pages With @ControllerAdvice
Throwing an exception from a controller is the cleanest way to say "this cannot continue". A @ControllerAdvice class turns those exceptions into proper pages for every controller.
package com.gocourse.web;
public class CourseNotFoundException extends RuntimeException {
public CourseNotFoundException(String code) {
super("We could not find a course called '" + code + "'.");
}
}
package com.gocourse.web;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class WebExceptionHandler {
@ExceptionHandler(CourseNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String courseNotFound(CourseNotFoundException ex, Model model) {
model.addAttribute("message", ex.getMessage());
return "course-not-found";
}
}
<!-- templates/course-not-found.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Course not found</h1>
<p th:text="${message}">Message</p>
<a th:href="@{/courses}">See all courses</a>
</body>
</html>
curl -s -i http://localhost:8080/courses/rust | head -n 1
curl -s http://localhost:8080/courses/rust | grep "<p>"
Output:
HTTP/1.1 404
<p>We could not find a course called 'rust'.</p>
How it works:
- Every controller in the application now shares this handler, so
CourseControllerandSeatControllerboth produce the same 404 page for unknown codes. @ResponseStatus(HttpStatus.NOT_FOUND)keeps the correct status code. A friendly page with status200would mislead browsers and search engines.th:textescapes HTML characters, which is why the quotes appear as'. User input shown withth:textcannot inject scripts. Useth:utextonly for HTML you fully trust.- In a
@ControllerAdvice, theModelparameter starts empty; the original controller's model is not carried over.
Real-World Example: Spring MVC Enquiry Form With Business Rules
The real enquiry form shows a drop-down of courses, rejects enquiries for full courses, and pre-selects a course when the user arrives from a course page (/enquiry?course=java). Validation annotations check the format; the controller adds the business rule.
package com.gocourse.web;
import jakarta.validation.Valid;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/v2/enquiry")
public class EnquiryController {
private final CourseCatalog catalog;
public EnquiryController(CourseCatalog catalog) {
this.catalog = catalog;
}
// Runs before every handler in this controller and adds "courses" to the model
@ModelAttribute("courses")
public List<Course> courses() {
return catalog.find(null, "title");
}
@GetMapping
public String form(@RequestParam(name = "course", required = false) String preselected, Model model) {
EnquiryForm form = new EnquiryForm();
form.setCourseCode(preselected);
model.addAttribute("enquiryForm", form);
return "enquiry-v2";
}
@PostMapping
public String submit(@Valid @ModelAttribute EnquiryForm enquiryForm, BindingResult result,
RedirectAttributes redirect) {
// Business rule on top of the annotation checks
if (!result.hasFieldErrors("courseCode")) {
catalog.byCode(enquiryForm.getCourseCode()).ifPresentOrElse(
course -> {
if (course.seatsLeft() == 0) {
result.rejectValue("courseCode", "course.full",
course.title() + " is full. Choose another course or join the waitlist.");
}
},
() -> result.rejectValue("courseCode", "course.unknown", "Please choose a course from the list"));
}
if (result.hasErrors()) {
return "enquiry-v2";
}
redirect.addFlashAttribute("notice",
"Thanks " + enquiryForm.getName() + "! Our " + enquiryForm.getCourseCode() + " mentor will reply soon.");
return "redirect:/enquiry/thanks";
}
}
<!-- templates/enquiry-v2.html (form part) -->
<form th:action="@{/v2/enquiry}" th:object="${enquiryForm}" method="post">
<input th:field="*{name}" placeholder="Name">
<input th:field="*{email}" placeholder="Email">
<select th:field="*{courseCode}">
<option value="">-- choose a course --</option>
<option th:each="course : ${courses}"
th:value="${course.code}"
th:text="${course.title} + (${course.seatsLeft == 0} ? ' (full)' : '')">Course</option>
</select>
<textarea th:field="*{message}"></textarea>
<ul th:if="${#fields.hasErrors('*')}">
<li class="error" th:each="error : ${#fields.errors('*')}" th:text="${error}">Error</li>
</ul>
<button>Send enquiry</button>
</form>
# 1. Arrive from the Java course page: the drop-down is pre-selected
curl -s "http://localhost:8080/v2/enquiry?course=java" | grep selected
# 2. Ask about a full course
curl -s -X POST http://localhost:8080/v2/enquiry \
-d "name=Ravi&email=ravi@example.com&courseCode=spring&message=When is the next batch?" | grep 'class="error"'
# 3. Valid enquiry, follow the redirect
curl -s -L -c jar.txt -b jar.txt -X POST http://localhost:8080/v2/enquiry \
-d "name=Meena&email=meena@example.com&courseCode=html&message=Do you cover Flexbox?" | grep "<p>"
Output:
<option value="java" selected="selected">Java Programming</option>
<li class="error">Spring Boot is full. Choose another course or join the waitlist.</li>
<body><p>Thanks Meena! Our html mentor will reply soon.</p></body>
How it works:
- Shared model data. The
@ModelAttribute("courses")method runs before bothformandsubmit, so the drop-down is filled on the first visit and again when the form is re-shown with errors. - Pre-filled forms. Setting
courseCodeon the form object before rendering makesth:fieldmark the matching<option>asselected. Links like/enquiry?course=javafrom each course page give a smoother path to enquiry. - Two layers of validation.
@Validchecks formats (blank fields, email shape).rejectValueadds business errors to the sameBindingResult, so the template shows both kinds the same way. The full-course check is skipped if the field already failed@NotBlank. - Collected error list.
#fields.errors('*')returns every error message, which suits short forms that show errors in one block. - Post/Redirect/Get. Success redirects to the thank-you page with a flash message, so refreshing the browser never sends the enquiry twice. The same pattern was written by hand with
sendRedirectin the Java Servlet lessons; Spring MVC reduces it to oneredirect:prefix.