MVC Architecture in JSP with Example

What is MVC?

MVC is an architecture that separates business logic, presentation and data. In MVC,

MVC is a systematic way to use the application where the flow starts from the view layer, where the request is raised and processed in controller layer and sent to model layer to insert data and get back the success or failure message.

Model Layer:

View Layer:

Controller Layer:

The diagram is represented below:

JSP MVC

The advantages of MVC are:

Example of MVC architecture

In this example, we are going to show how to use MVC architecture in JSP.

Mvc_example.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>MVC Guru Example</title>
</head>
<body>
<form action="Mvc_servlet" method="POST">
Email: <input type="text" name="email">
<br />
Password: <input type="text" name="password" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Explanation of the code:

View Layer:

Code Line 10-15: Here we are taking a form which has two fields as parameter "email" and "password" and this request need to be forwarded to a controller Mvc_servlet.java, which is passed in action.The method through which it is passed is POST method.

Mvc_servlet.java

package demotest;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Mvc_servlet
 */
public class Mvc_servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Mvc_servlet() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String email=request.getParameter("email");  
        String password=request.getParameter("password");
        
        TestBean testobj = new TestBean();
        testobj.setEmail(email);
        testobj.setPassword(password);
        request.setAttribute("gurubean",testobj);
        RequestDispatcher rd=request.getRequestDispatcher("mvc_success.jsp");  
        rd.forward(request, response); 
	}

}

Explanation of the code:

Controller layer

Code Line 14:mvc_servlet is extending HttpServlet.

Code Line 26: As the method used is POST hence request comes into a doPost method of the servlet which process the requests and saves into the bean object as testobj.

Code Line 34: Using request object we are setting the attribute as gurubean which is assigned the value of testobj.

Code Line 35: Here we are using request dispatcher object to pass the success message to mvc_success.jsp

TestBean.java

package demotest;

import java.io.Serializable;

public class TestBean implements Serializable{
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	private String email="null";
	private String password="null";


}

Explanation of the code:

Model Layer:

Code Line 7-17: It contains the getters and setters of email and password which are members of Test Bean class

Code Line 19-20: It defines the members email and password of string type in the bean class.

Mvc_success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@page import="demotest.TestBean"%>
<!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>Guru Success</title>
</head>
<body>
<%  
TestBean testguru=(TestBean)request.getAttribute("gurubean");  
out.print("Welcome, "+testguru.getEmail());  
%>
</body>
</html>

Explanation of the code:

Code Line 12: we are getting the attribute using request object which has been set in the doPost method of the servlet.

Code Line 13: We are printing the welcome message and email id of which have been saved in the bean object

Output:

When you execute the above code, you get the following output:

When you click on mvc_example.jsp you get the form with email and password with the submit button.

Once you enter email and password to the form and then click on submit

JSP MVC

After clicking on submit the output is shown as below

JSP MVC

Output:

When you enter email and password in screen and click on submit then, the details are saved in TestBean and from the TestBean they are fetched on next screen to get the success message.

Summary:

In this article, we have learnt about the MVC i.e. Model View Controller architecture.

JSP plays the role of presentation of the data and controller. It is an interface between model and view while model connects both to the controller as well as the database. Main business logic is present in the model layer.

 

YOU MIGHT LIKE: