MVC Architecture with JSP example
Model-View-Controller (MVC) is a software architectural pattern that separates an application into three main logical components: the model, the view, and the controller.
Model: The model represents the underlying, logical structure of data in a software application and the high-level class associated with it. It represents the business logic and the underlying data.
View: The view is responsible for presenting the model to the user. It is a visual representation of the model and is rendered on the screen.
Controller: The controller is the intermediary between the model and the view. It receives input from the user, updates the model as needed, and presents the updated model to the view.
The MVC pattern helps to separate the concerns of the different parts of the application, making it easier to develop, maintain, and test.
There has been a shift in recent years away from traditional MVC frameworks towards more modern, component-based architectures such as React and Angular. These frameworks are often referred to as “single-page applications” (SPAs) because they can handle all the rendering and updating of the page on the client side, without the need for the server to send a new page with each request.
However, traditional MVC frameworks are still widely used and continue to be popular choices for building web applications. Some examples of popular MVC frameworks include ASP.NET MVC, Ruby on Rails, and Spring MVC.
It is also worth noting that the MVC pattern is not limited to web applications. It can be applied to other types of software as well, such as desktop applications and mobile apps.
Try reading this book for most asked Java interview questions: https://amzn.to/3ivsW5o
MVC Example with JSP:
The following example consists of three .jsp files, one servlet and a bean class. The servlets and beans placed appropriately in the corresoonding packages viz. controller and beans.
index.jsp — A page that gets input from the user.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<form action="ControllerServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br> <br>
<input type="submit" value="login">
</form>
ControllerServlet.java — A servlet that acts as a controller.
@WebServlet(urlPatterns = {"/ControllerServlet"})
public class ControllerServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name = request.getParameter("name");
String password = request.getParameter("password");
LoginBean bean = new LoginBean();
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean", bean);
boolean status = bean.validate();
if (status) {
RequestDispatcher rd = request.getRequestDispatcher("login_success.jsp");
rd.forward(request, response);
}
else {
RequestDispatcher rd = request.getRequestDispatcher("login_error.jsp");
rd.forward(request, response);
}
}
}
LoginBean.java — A java bean (POJO) with name and password as properies. It validates users with password ‘admin’.
package beans;
public class LoginBean {
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LoginBean() {
}
public boolean validate(){
if(password.equals("admin")){
return true;
}
else{
return false;
}
}
}
login-success.jsp and login-error.jsp files acts as view components.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="beans.LoginBean"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Success JSP Page</title>
</head>
<body>
<p>You are successfully logged in!</p>
<%
LoginBean bean = (LoginBean) request.getAttribute("bean");
out.print("Welcome, " + bean.getName());
%>
</body>
</html>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error JSP Page</title>
</head>
<body>
<p>Sorry! Credentials doesn't match</p>
<%@ include file="index.jsp" %>
</body>
</html>
Separation of concerns is one of the most attractive concepts of the MVC pattern. The complexity of modern web applications can make it difficult to make changes. When the frontend and backend are separated, the application is scalable, maintainable, and easy to expand.
Thanks for reading! Happy Coding!!