MVC (Model-View-Controller, Model-View-Controller) is a design pattern used to separate an application's business logic, data, and user interface. In Java Web development, the MVC design pattern helps to achieve code modularity and maintainability. The following is a brief introduction to each component of MVC:
- Model (model): Represents data and business logic. Usually includes data access objects (DAO) and JavaBean (such as entity classes, POJO).
- View (view): represents the user interface. Usually JSP pages, HTML, CSS and JavaScript etc.
- Controller: Passes data and instructions between the model and the view. Usually implemented with Servlets.
8.4.1. Example: Building a Java Web Application Using the MVC Design Pattern
The following is an example of a simple Java web application that implements a user login function using the MVC design pattern.
- Create a
LoginMVC
web application directory structure called:
LoginMVC/
|-- WEB-INF/
| |-- classes/
| | |-- controller/
| | | |-- LoginController.class
| | |-- model/
| | | |-- UserDao.class
| | | |-- User.class
| |-- lib/
| |-- web.xml
|-- login.jsp
|-- welcome.jsp
- Write
User
the class (model):
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- Write
UserDao
the class (model):
import java.util.HashMap;
import java.util.Map;
public class UserDao {
private static final Map<String, String> userData = new HashMap<>();
static {
userData.put("admin", "password");
userData.put("user", "1234");
}
public User getUserByUsername(String username) {
String password = userData.get(username);
if (password != null) {
return new User(username, password);
}
return null;
}
}
- Write
LoginController
the class (controller):
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "LoginController", urlPatterns = "/login")
public class LoginController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDao userDao = new UserDao();
User user = userDao.getUserByUsername(username);
if (user != null && password.equals(user.getPassword())) {
request.setAttribute("user", user);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
} else {
request.setAttribute("errorMessage", "Invalid username or password");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
- Write
login.jsp
a file (view):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<input type="submit" value="Login">
</form>
<p style="color:red;"><%= request.getAttribute("errorMessage") %></p>
</body>
</html>
- Write
welcome.jsp
a file (view):
jsp
Copy
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <%= ((User) request.getAttribute("user")).getUsername() %>!</h1>
</body>
</html>
- Write
web.xml
the file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>LoginController</servlet-name>
<servlet-class>controller.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Now, when the user visits login.jsp
the page and enters their username and password, the form will be submitted to LoginController
. The controller queries UserDao
for user data and, depending on the validation result, redirects the user to welcome.jsp
a page or displays an error message.
By using the MVC design pattern, we separate the different parts of the application, making it easier to maintain and extend. Recommended reading: