Back to: JSP Tutorials for Beginners and Professionals
MVC in JSP Application with Example
In this article, I am going to discuss MVC in JSP Application with Examples. Please read our previous article where we discussed Internationalization in JSP Application.
What is MVC?
MVC stands for Model-View-Controller. It is a design pattern used for developing web applications. It is a layout pattern used to isolate the information, presentation logic, business logic. Web application Logic is divided into three logics:
- Presentation Logic
- Business Logic
- Persistent Logic
Each one is called Model or Tier. MVC is popular because it isolates the appliance logic from the interface layer and supports the separation of concerns. Here the Controller receives all requests for the appliance then works with the Model to organize any data needed by the View. The View then uses the information prepared by the Controller to get a final presentable response. The MVC abstraction is often graphically represented as follows.
What is the Model?
It is a module or tier which contains persistent logic or database operation. The model uses JDBC, Hibernate, JPA. The Model segment compares each one among the knowledge-related rationale that the client works with. This can speak to either the information that is being exchanged between the View and Controller segments or some other business-related information.
What is a Controller?
The controller controls the flow of execution of web applications. In web application development servlet is called a controller. Controller receive request/input from the client and uses other modules to perform operations. The controller contains Business Logic. Controllers set about as an interface amongst Model and consider segments to process all the business rationale and approaching solicitations, control information utilizing the Model part and cooperate with the Views to render the last yield.
What is View?
The view is used for generating input and output. It contains presentation logic. This is developed using HTML or JSP. The View part is utilized for all the UI rationale of the application.
Advantages of MVC
- The main advantage of using MVC in a Web Application is it makes complex applications easy to manage with divisions of Model, View, and Controllers.
- MVC provides a strong routing mechanism with a Front Controller pattern.
- MVC works well for development with large teams with multiple web developers and designers working simultaneously.
- In MVC, separating the model from View makes the web application more robust and easier to maintain.
- In MVC, separating the Controller from the Model allows configurable mapping of user actions on the Controller to application functions on the Model.
Example of MVC in JSP Application
In this example, we are showing how to use MVC architecture in JSP. In this example, we are creating an example in which servlet as a controller, JSP as a view component, Java Bean class as a model. In this example, we have created 6 pages.
- index.jsp
- ControllerServlet.java
- LoginBean.java
- login-success.jsp
- login-error.jsp
- web.xml
Where index.jsp helps us to get the input from the user. ControllerServlet.java acts as a controller, login-success.jsp and login-error.jsp file acts as a view component. Login-success.jsp page will show the “Welcome” message if the user will successfully login whereas login-error.jsp page will show the error message and returns you back to the index.jsp page. LoginBean.java acts as a Model Layer and a web.xml file is used to mapping the servlet.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="ControllerServlet" method="post"> Name:<input type="text" name="name"><br> Password:<input type="password" name="password"><br> <input type="submit" value="login"> </form> </body> </html>
LoginBean.java
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 boolean validate() { if (password.equals("admin")) { return true; } else { return false; } } }
ControllerServlet.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ControllerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); 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); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
login-succes.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title></title> </head> <body> <% out.print("Welcome"); %> </body> </html>
login-error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <p>Sorry! username or password error</p> <%@ include file="index.jsp"%> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>s1</servlet-name> <servlet-class>ControllerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/ControllerServlet</url-pattern> </servlet-mapping> </web-app>
Output
Run your code to get the following output. Enter your Name(any) and Password as “admin” and then click on the “login” button.
After clicking on the “login” button, if your password is correct, you will get the following output.
After clicking on the “login” button, if your password is incorrect, you will get the error message and you will be directed back to the index page.
In the next article, I am going to discuss Debugging in JSP Applications. Here, in this article, I try to explain MVC in JSP Applications and I hope you enjoy MVC in JSP Application with Examples article.
where is validation part bro?