MVC architecture example with Servlets and JSP

  •  
  •  
  •  
  •  
  •  
  •  

In this tutorial, MVC architecture example with Servlets and JSP, we will create a small web application that implements the MVC (Model View Controller) pattern, using simple Servlets and JSP programming.

But, at first, we will try to understand the basic knowledge about what is MVC and how it works before we move on to the actual implementation.

MVC architecture example with Servlets and JSP

Introduction to MVC Architecture

Model View Controller (MVC) is a software design architectural pattern for developing the web application. MVC pattern separates business logic, presentation, and data. MVC pattern has the following three parts —

  1. Model – This level is responsible for all kinds of business logic operations. It has the classes which have the connection with the database.
  2. View – This is the presentation layer which consists of HTML, JSP pages. This layer is responsible for displaying the application’s output to the end users.
  3. Controller – This layer handles the HTTP requests and sends to the appropriate Model layer for data processing, and once the data are processed and sent back to the controller and then displayed on the View layer.

MVC architecture example Servlets and JSP

Now, first, create a Dynamic Web Project in Eclipse IDE by clicking on the following options — File->New->Dynamic Web Project. Also, you can visit the following tutorial where you can learn how to create a new dynamic web project in Eclipse IDE.

Project Folder Structure

Below image is the final project folder structure, please have a look at it —

Project folder structure of MVC architecture example with Servlets and JSP

In our MVC web application, we have six JSP pages in which header.jsp, footer.jsp and menu.jsp are included in the other three JSP pages. To implement web-based MVC design pattern, we will create Login.java and LoginLogoutServlet.java classes which will act as our Model layer. Further, LoginLogoutServlet.java is also acting as a Controller class.

Let’s start the code.

Login.java (Model Layer)

package com.mit.model;

import java.io.Serializable;


public class Login implements Serializable {
  
  private String username;
  
  private String 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;
  }
}

This model class contains the getter and setter methods of username and password which are members of the Login class.

LoginLogoutServlet.java (Controller Layer)

package com.mit.servlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

@WebServlet({ "/login", "/logout" })
public class LoginLogoutServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    
    public LoginLogoutServlet() {
        super();
    }

  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String path = request.getServletPath();
    HttpSession session = request.getSession();
    if(path.equals("/login")) {
      /**
       * After successful login if any user again try to load the login page
       * it will redirects to the home page
       */
      if(session.getAttribute("loggedin_username") == null) {
        RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
        dispatcher.forward(request, response);
      } else {
        response.sendRedirect(request.getContextPath());
      }
    } else if(path.equals("/logout")) {	
      /**
       * Invalidate or destroy the session attributes
       * and redirects to the home page
       */
      session.invalidate();
      response.sendRedirect(request.getContextPath());
    }
  }

  
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    /**
     * Here we checked username and password with pre-defined values.
     * You can check username and password by fetching them from database.
     */
    if(username.equals("mitrajit") && password.equals("pass1234")) {
      setUserSession(username, request);			
      response.sendRedirect(request.getContextPath());
    } else {
      request.setAttribute("err", "Invalid username and password!");
      RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
      dispatcher.forward(request, response);
    }
  }
  
  
  /**
   * Set user information in session attribute
   * @param username
   * @param request
   */
  protected void setUserSession(String username, HttpServletRequest request) {
    HttpSession session = request.getSession();
    session.setAttribute("loggedin_username", username);
  }

}

@WebServlet annotation used to declare a Java class as a Servlet. Here the LoginLogoutServlet is mapped with the multiple URL /login and /logout. When the user tries to load the /login page it will forward the request from the servlet to another resource in that case login.jsp. And when the user tries to log out it will invalidate or destroy the HTTP Session and redirects to the Home page.

Login.jsp (View Layer)

<jsp:include page="includes/header.jsp" />

  <h2 class="page-header">Login</h2>
  
  <div class="centered">
    <div class="login-div">
      <form action="login" method="post">
        <div class="container">
          <label for="username"><b>Username</b></label>
          <input type="text" placeholder="Enter Username" name="username" value="" required>
      
          <label for="psw"><b>Password</b></label>
          <input type="password" placeholder="Enter Password" name="password" value="" required>
              
          <button type="submit">Login</button>
          <label><span class="error">${err}</span></label>
        </div>
      </form>
    </div><!-- .login-div -->
  </div><!-- .centered -->

<jsp:include page="includes/footer.jsp" />

Login.jsp is the View or Presentation layer which is responsible for displaying the output to the users. It doesn’t require to interact with the business layer directly.

Similarly, I created another two Servlet class which are acting as the controller for About Us and Home page respectively. There is no Model layer is associated with these two Servlets and JSP pages because in this example no business logic or database related operation is performed for these two pages.

HomeServlet.java (Controller Layer)

package com.mit.servlets;

import java.io.IOException;

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

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet(urlPatterns={"/"})
public class HomeServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  
    public HomeServlet() {
        super();
    }

  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/index.jsp");
    dispatcher.forward(request, response);
  }
}

This servlet class is mapped with the base URL (home page). When someone types http://localhost:8080/jsp-servlet-mvc/ and press enter it will forward the request to the index.jsp page.

index.jsp (Model Layer)

<jsp:include page="includes/header.jsp" />

  <h2 class="page-header">Home</h2>
  
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.</p>

<jsp:include page="includes/footer.jsp" />

AboutUsServlet.java (Controller Layer)

package com.mit.servlets;

import java.io.IOException;

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

/**
 * Servlet implementation class AboutUsServlet
 */
@WebServlet("/about-us")
public class AboutUsServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    public AboutUsServlet() {
        super();
    }

  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/views/about-us.jsp");
    dispatcher.forward(request, response);
  }
}

about-us.jsp (Model Layer)

<jsp:include page="includes/header.jsp" />

  <h2 class="page-header">About Us</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

<jsp:include page="includes/footer.jsp" />

Deployment Descriptor (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>jsp-servlet-mvc</display-name>
  <welcome-file-list>
    <welcome-file>/</welcome-file>
  </welcome-file-list>
</web-app>

That’s all friends. Now its time to run our MVC web application in the browser. Paste the following link in the browser — http://localhost:8080/jsp-servlet-mvc/

Home Page

Home Page -- MVC architecture example with Servlets and JSP

 

About Us Page

About Us Page -- MVC architecture example with Servlets and JSP

 

Login Page

Login Page -- MVC architecture example with Servlets and JSP

You can see how easily we can implement MVC architecture with Servlets and JSP.

If you face any problem feel free to inform me in the comment section below. Please like and share this tutorial MVC architecture with Servlets and JSP with others. Kindly subscribe Mitrajit’s Tech Blog to keep yourself updated with the upcoming article.

About Mitrajit

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove you are a human *