MVC Architecture in JSP with Example - Javastudypoint

Thursday, December 20, 2018

MVC Architecture in JSP with Example

MVC stands for Model View Controller. It is a design pattern which is used to separate the business logic, presentation logic and data. It can be used to design a web application in a standard manner ie: It will provide a pattern to design web application. It is able to define which element is used for which purpose. As per MVC, our application will be divided into three layers.




1.Model Layer:

  • Model Layer is the data layer.
  • It consists of all the data of our web application.
  • It represents a state of an application.
  • The Model Layer is responsible to connect with the database as well as stores the data into a database.
  • It consists of all the classes in our application which have the connection to the database.

2. View Layer:

  • It represents the presentation layer
  • It normally represents the User Interface (UI) of the application.
  • We can use HTML,CSS,JS etc to create presentation layer.

3. Controller Layer:

  • It is an interface between the view layer and the model layer.
  • It receives the request from View Layer.
  • It read the data which is coming from the presentation layer.
  • To read data from the presentation layer, we can use Servlet, JSP, Filter, etc.

The MVC Architecture is given below:

MVC Architecture in jsp
MVC Architecture

The advantage of MVC architecture are:

  • It is easy to maintain.
  • It is easy to test.
  • It is easy to extend.
  • The navigation control is centralized.

Example of MVC architecture:

In this example, we are going to show you how to use MVC architecture in JSP. In this example, we are going to create 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: It gets the input from the user.
ControllerServlet.java: It acts as a controller.
loginSuccess and loginError.jsp files acts as a view component.
LoginMvcBean.java: It acts as a Model layer.
web.xml file is used to mapping the servlet.

index.jsp
MVC Architecture in jsp

ControllerServlet.java
MVC Architecture in jsp

LoginMvcBean.java
MVC Architecture in jsp




loginSuccess.jsp
MVC Architecture in jsp


loginError.jsp
MVC Architecture in jsp

web.xml
MVC Architecture in jsp


Output: When we enter the right credential.

MVC Architecture in jsp


MVC Architecture in jsp



Output: When we enter the wrong credential.

MVC Architecture in jsp



MVC Architecture in jsp



You may also like:
Life Cycle of a JSP Page
JSP Scripting Elements - Scriptlet, Declaration and Expression
9 Implicit objects in JSP
JSP Directives - Page, include and taglib
JSP Action Tags - jsp useBean, jspInclude and jspForward



No comments:

Post a Comment