Java Notes
Complete guide to Model-View-Controller (MVC) pattern in Java web applications - implementing MVC with Servlets and JSP, Front Controller pattern, and practical examples.
What is MVC?
MVC (Model-View-Controller) is a design pattern that separates an application into three interconnected components:
- Model — Data and business logic (JavaBeans, POJOs, Services)
- View — Presentation layer (JSP pages, HTML templates)
- Controller — Handles requests, coordinates Model and View (Servlets)
Why MVC?
| Without MVC | With MVC |
|---|---|
| HTML mixed with Java logic | Clean separation |
| Hard to test | Easy unit testing |
| One developer does everything | Team can work in parallel |
| Changes break other parts | Changes isolated to one layer |
| Code duplication | Reusable components |
Implementing MVC: Student Management Example
Model Layer
Student.java (JavaBean/POJO)
package com.example.model;
public class Student {
private int id;
private String name;
private String email;
private int age;
private String course;
public Student() {}
public Student(int id, String name, String email, int age, String course) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
this.course = course;
}
// Getters and Setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
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 int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getCourse() { return course; }
public void setCourse(String course) { this.course = course; }
}StudentDAO.java (Data Access Object)
package com.example.dao;
import com.example.model.Student;
import java.sql.*;
import java.util.*;
public class StudentDAO {
private Connection connection;
public StudentDAO(Connection connection) {
this.connection = connection;
}
public List<Student> getAllStudents() throws SQLException {
List<Student> students = new ArrayList<>();
String sql = "SELECT * FROM students ORDER BY id";
try (PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
students.add(mapRow(rs));
}
}
return students;
}
public Student getById(int id) throws SQLException {
String sql = "SELECT * FROM students WHERE id = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, id);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) return mapRow(rs);
}
}
return null;
}
public void insert(Student student) throws SQLException {
String sql = "INSERT INTO students (name, email, age, course) VALUES (?, ?, ?, ?)";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, student.getName());
ps.setString(2, student.getEmail());
ps.setInt(3, student.getAge());
ps.setString(4, student.getCourse());
ps.executeUpdate();
}
}
public void update(Student student) throws SQLException {
String sql = "UPDATE students SET name=?, email=?, age=?, course=? WHERE id=?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, student.getName());
ps.setString(2, student.getEmail());
ps.setInt(3, student.getAge());
ps.setString(4, student.getCourse());
ps.setInt(5, student.getId());
ps.executeUpdate();
}
}
public void delete(int id) throws SQLException {
String sql = "DELETE FROM students WHERE id = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, id);
ps.executeUpdate();
}
}
private Student mapRow(ResultSet rs) throws SQLException {
return new Student(
rs.getInt("id"),
rs.getString("name"),
rs.getString("email"),
rs.getInt("age"),
rs.getString("course")
);
}
}StudentService.java (Business Logic)
Controller Layer
StudentController.java (Servlet)
View Layer
student-list.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>Student Management</title></head>
<body>
<h2>Students (${totalCount})</h2>
<c:if test="${not empty sessionScope.message}">
<p style="color:green">${sessionScope.message}</p>
<c:remove var="message" scope="session" />
</c:if>
<a href="${pageContext.request.contextPath}/students/add">Add New Student</a>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Email</th>
<th>Age</th><th>Course</th><th>Actions</th>
</tr>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>${student.age}</td>
<td>${student.course}</td>
<td>
<a href="${pageContext.request.contextPath}/students/edit?id=${student.id}">Edit</a>
<a href="${pageContext.request.contextPath}/students/delete?id=${student.id}"
onclick="return confirm('Delete this student?')">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>student-form.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><title>${empty student ? "Add" : "Edit"} Student</title></head>
<body>
<h2>${empty student ? "Add New" : "Edit"} Student</h2>
<c:if test="${not empty error}">
<p style="color:red">${error}</p>
</c:if>
<form method="POST" action="${pageContext.request.contextPath}/students/${empty student ? 'add' : 'edit'}">
<c:if test="${not empty student}">
<input type="hidden" name="id" value="${student.id}" />
</c:if>
<label>Name:</label><br>
<input type="text" name="name" value="${student.name}" required /><br><br>
<label>Email:</label><br>
<input type="email" name="email" value="${student.email}" required /><br><br>
<label>Age:</label><br>
<input type="number" name="age" value="${student.age}" min="16" max="60" required /><br><br>
<label>Course:</label><br>
<select name="course">
<option value="Java" ${student.course == 'Java' ? 'selected' : ''}>Java</option>
<option value="Python" ${student.course == 'Python' ? 'selected' : ''}>Python</option>
<option value="Web Development" ${student.course == 'Web Development' ? 'selected' : ''}>Web Development</option>
</select><br><br>
<button type="submit">Save</button>
<a href="${pageContext.request.contextPath}/students/list">Cancel</a>
</form>
</body>
</html>Front Controller Pattern
A Front Controller is a single servlet that handles ALL requests and dispatches to appropriate handlers:
@WebServlet("/app/*")
public class FrontController extends HttpServlet {
private Map<String, RequestHandler> handlers = new HashMap<>();
@Override
public void init() {
handlers.put("/students", new StudentHandler());
handlers.put("/courses", new CourseHandler());
handlers.put("/reports", new ReportHandler());
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getPathInfo();
RequestHandler handler = findHandler(path);
if (handler != null) {
handler.handle(request, response);
} else {
response.sendError(404);
}
}
}This is essentially what Spring MVC's DispatcherServlet does!
Project Structure (MVC)
MVC Benefits Summary
| Benefit | Explanation |
|---|---|
| Separation of Concerns | Each layer has one job |
| Testability | Model and Service tested independently |
| Parallel Development | Frontend/Backend developers work separately |
| Reusability | Models reused across different views |
| Maintainability | Change view without touching logic |
| Scalability | Easy to add new features |
Interview Key Points
- MVC separates data (Model), UI (View), and logic (Controller)
- In Java web apps: Model=JavaBeans, View=JSP, Controller=Servlet
- Controller receives request, calls Model, forwards to View
- JSP pages should NEVER be directly accessible (put in WEB-INF)
- Front Controller pattern = single entry point for all requests
- Spring MVC is a sophisticated implementation of this pattern
- DAO pattern separates database logic from business logic
Summary
In this chapter, we learned about MVC Architecture in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Key Takeaways for Mvc Architecture
- This topic is fundamental in Java development and is frequently asked in interviews
- Make sure to do hands-on practice for practical implementation
- Understanding its use in real-world projects is important for writing production-ready code
- Keep referring to documentation and official Java docs for the latest updates
- Also develop testing and debugging skills alongside this topic
- Follow industry best practices and actively participate in code reviews
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for MVC Architecture.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, mvc
Related Java Master Course Topics