-
Notifications
You must be signed in to change notification settings - Fork 0
YourNote 701: MVC Pattern in JEE
Zhamri Che Ani edited this page Jun 13, 2026
·
1 revision
MVC (Model-View-Controller) is a design pattern used in JEE web applications where Servlets act as Controllers, JSP pages act as Views, and JavaBeans/DAO classes act as Models, providing a clear separation between presentation, business logic, and data access.
The Model contains:
- Business logic
- Data processing
- Database access (JDBC, JPA, Hibernate)
- JavaBeans
Example:
public class Student {
private String matricNo;
private String name;
// Getter and Setter
}or
public class StudentDAO {
public Student getStudent(String matricNo) {
// Retrieve data from database
}
}The View is responsible for:
- User Interface
- Displaying data
- Receiving user input
In JEE, View is usually:
- JSP
- HTML
- CSS
- JavaScript
Example:
<h2>Student Information</h2>
<p>Name: ${student.name}</p>
<p>Matric No: ${student.matricNo}</p>The View should NOT contain database code.
The Controller acts as the middleman.
Responsibilities:
- Receive user requests
- Validate input
- Call Model
- Send data to View
In JEE, Controller is usually a Servlet.
Example:
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
StudentDAO dao = new StudentDAO();
Student student = dao.getStudent("A123");
request.setAttribute("student", student);
RequestDispatcher rd =
request.getRequestDispatcher("student.jsp");
rd.forward(request, response);
}
}Browser
|
| Request
v
Servlet (Controller)
|
| Calls
v
Model (JavaBean/DAO)
|
| Returns Data
v
Servlet (Controller)
|
| Forward
v
JSP (View)
|
| Response
v
Browser
- User opens:
http://localhost:8080/login.jsp
- Request goes to Servlet.
- Servlet calls DAO.
- DAO retrieves data from MySQL.
- DAO returns data to Servlet.
- Servlet stores data:
request.setAttribute("student", student);- Servlet forwards to JSP.
- JSP displays the data.
- Browser shows the result.
StudentMVC
│
├── src
│ └── my/zhamri
│ ├── Student.java
│ ├── StudentDAO.java
│ └── StudentServlet.java
│
├── webapp
│ ├── student.jsp
│ └── index.jsp
│
└── WEB-INF
| Advantage | Description |
|---|---|
| Separation of Concerns | Each component has a specific responsibility |
| Easier Maintenance | Changes can be made independently |
| Reusability | Model can be reused by different views |
| Better Testing | Components can be tested separately |
| Team Development | Frontend and backend can work independently |
<%
Connection con =
DriverManager.getConnection(...);
Statement stmt =
con.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM student");
%>Problems:
- SQL inside JSP
- Difficult to maintain
- Difficult to debug
- Poor scalability