Model View Controller(MVC) in Java web Project

What is Model View Controller(MVC)? and the Importance of MVC in a Java web project. In this Java web application development tutorial, Let’s discuss the MVC and how to implement MVC in a real-time java project.

What is Model View Controller?

MVC is an architecture to develop the software application. MVC divides the project development process into 3 parts Model, Controllers, and View.

Each application(Web, Mobile, or Desktop) depends on 3 major parts Client(User view ), Server(Handle the user request), and Database(database transaction as per the user request). let’s understand these 3 MVC components in detail.

Model

Under the model section, we keep all the classes that contain the code for all the database transactions like custom methods to ADD, DELETE and UPDATE records.

Model is a separate package in the project that contains all the classes that are responsible to handle the database transaction.

View

The view is the user interaction part of the application where the user can see an interface to perform the operations in the application all the visible parts of the application will come under the view.

All the designing parts will come under the view section that is developed into HTML, CSS, and Bootstrap.

Controller

The controller will work as a mediator.  It handles the request and response for the view and model part. The controller is acting like a brain that accepts requests from the view validates the data and sends it to the model. Again at the same time get the response form model, Understand the response convert it into a message and send it to view.

Importance of MVC architecture

  • Make the development process fast.
  • Remove the technology dependencies.
  • Make the process more flexible.
  • Improve code reusability.
  • Test-Driven Development (Provide facility to test each state separately).
  • Common architecture makes the development understandable for new devs.

Implement MVC in a java web project

Java is a wide programming language that provides multiple tech stacks to develop a web application. For Example, We can develop a web application in java using HTML, CSS, Bootstrap, JSP, Servlet, MYSQL(JDBC), OR HTML, CSS, Bootstrap, Spring, and Hibernate OR AngularJS, ReactJS, Rest API with spring boot and hibernate.

In this example, Let’s use the core technologies(HTML, CSS, Bootstrap, JSP, Servlet, MYSQL(JDBC)) and divide them according to the MVC architecture.

View

HTML, CSS, Bootstrap, and all these technologies come under the view part. Just keep in mind(What you can see over the screen will come under the view part) It can be a Button, Link, Input, Text, Slider, or Image.

If I talk about the specific Java project view will come under the webapp folder

Sample code for login view (loginview.jsp)

<%@page import="com.tourism.mgt.ctl.LoginCtl"%>
<%@page import="com.tourism.mgt.util.DataUtility"%>
<%@page import="com.tourism.mgt.util.ServletUtility"%>
<%@ 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>
    <%@ include file="Header.jsp"%>
    <br>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb pink lighten-4">
            <li class="breadcrumb-item"><a class="black-text" href="<%=TMSView.WELCOME_CTL%>">Home</a></li>
            <li class="breadcrumb-item active">Login</li>
        </ol>
    </nav>

    <!-- Material form subscription -->
    <div class="container">
        <div class="row">
            <div class="col-sm-3"></div>
            <div class="col-sm-6">


                <div class="card">

                    <h5 class="card-header info-color white-text text-center py-4">
                        <strong>Login</strong>
                    </h5>

                    <!--Card content-->
                    <div class="card-body px-lg-5">

                        <!-- Form -->
                        <form class="text-center" style="color: #757575;"
                            action="<%=TMSView.LOGIN_CTL%>" method="post">
                            <jsp:useBean id="bean" class="com.tourism.mgt.bean.UserBean"
                                scope="request"></jsp:useBean>
                            <%
                                String uri = (String) request.getAttribute("uri");
                            %>

                            <input type="hidden" name="uri" value="<%=uri%>"> <input
                                type="hidden" name="id" value="<%=bean.getId()%>"> <input
                                type="hidden" name="createdBy" value="<%=bean.getCreatedBy()%>">
                            <input type="hidden" name="modifiedBy"
                                value="<%=bean.getModifiedBy()%>"> <input type="hidden"
                                name="createdDatetime"
                                value="<%=DataUtility.getTimestamp(bean.getCreatedDatetime())%>">
                            <input type="hidden" name="modifiedDatetime"
                                value="<%=DataUtility.getTimestamp(bean.getModifiedDatetime())%>">
                            <p>
                                <b><font color="red"><%=ServletUtility.getErrorMessage(request)%></font></b>
                                <b><font color="green"><%=ServletUtility.getSuccessMessage(request)%></font></b>
                            </p>

                            <!-- Name -->
                            <div class="md-form mt-3">
                                <input type="text" class="form-control" name="login"
                                    value="<%=DataUtility.getStringData(bean.getLogin())%>">
                                <label for="materialSubscriptionFormPasswords">Login Id</label>
                                <font color="red" style="font-size: 13px"><%=ServletUtility.getErrorMessage("login", request)%></font>
                            </div>

                            <!-- E-mai -->
                            <div class="md-form">
                                <input type="password" class="form-control" name="password"
                                    value="<%=DataUtility.getStringData(bean.getPassword())%>">
                                <label for="materialSubscriptionFormEmail">Password</label> <font
                                    color="red" style="font-size: 13px"><%=ServletUtility.getErrorMessage("password", request)%></font>
                            </div>

                            <!-- Sign in button -->

                            <input type="submit" name="operation"
                                class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect"
                                value="<%=LoginCtl.OP_SIGN_IN%>"> or <input type="submit"
                                name="operation"
                                class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect"
                                value="<%=LoginCtl.OP_SIGN_UP%>"> <br>
                            <!-- <br> <a href="#">Forget Password ?</a> -->

                        </form>
                        <!-- Form -->

                    </div>

                </div>
                <!-- Material form subscription -->
                <div class="col-sm-3"></div>
            </div>
        </div>
    </div>
    <br>
    <%@ include file="Footer.jsp"%>
</body>
</html>

Controllers

The controller is a custom package that contains all the servlets that are responsible to handle the request that is coming from view and the response that is coming from models.

Role of controllers(Servlet)

  • Get Request and response.
  • Send a request and response.
  • Forward request and response.
  • Redirect request and response
  • Send error or success messages with request and response

Sample Controller for login(LoginCtl.java)

package com.tourism.mgt.ctl;

import java.io.IOException;

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;

import org.apache.log4j.Logger;

import com.tourism.mgt.bean.BaseBean;
import com.tourism.mgt.bean.UserBean;
import com.tourism.mgt.exception.ApplicationException;
import com.tourism.mgt.model.UserModel;
import com.tourism.mgt.util.DataUtility;
import com.tourism.mgt.util.DataValidator;
import com.tourism.mgt.util.PropertyReader;
import com.tourism.mgt.util.ServletUtility;



@WebServlet(name = "LoginCtl", urlPatterns = { "/login" })
public class LoginCtl extends BaseCtl {

    private static final long serialVersionUID = 1L;
    
    public static final String OP_REGISTER = "Register";
    public static final String OP_SIGN_IN = "SignIn";
    public static final String OP_SIGN_UP = "SignUp";
    public static final String OP_LOG_OUT = "logout";
    public static String HIT_URI = null;
    
    private  static Logger log = Logger.getLogger(LoginCtl.class);


    public LoginCtl() {
        super();
        // TODO Auto-generated constructor stub
    }

    
    protected boolean validate(HttpServletRequest request) {

        log.debug("LoginCtl Method validate Started");
        
        boolean pass = true;
        
        String op = request.getParameter("operation");
        
        if (OP_SIGN_UP.equals(op) || OP_LOG_OUT.equals(op)) {
            return pass;
        }
        
        
        String login = request.getParameter("login");
        
        if (DataValidator.isNull(login)) {
            request.setAttribute("login", PropertyReader.getValue("error.require", "Login Id"));
            pass = false;
        
        } else if (!DataValidator.isEmail(login)) {
            request.setAttribute("login", PropertyReader.getValue("error.email", "Login Id "));
            pass = false;
        }
        if (DataValidator.isNull(request.getParameter("password"))) {
            request.setAttribute("password", PropertyReader.getValue("error.require", "Password"));
            pass = false;
        }
        log.debug("LoginCtl Method validate Ended");
        return pass;
    }

    /**
     * Populates bean object from request parameters
     * 
     * @param request
     * @return
     */
    protected BaseBean populateBean(HttpServletRequest request) {

        log.debug("LoginCtl Method populateBean Started");

        UserBean bean = new UserBean();
        
        bean.setId(DataUtility.getLong(request.getParameter("id")));
        
        bean.setLogin(DataUtility.getString(request.getParameter("login")));
        
        bean.setPassword(DataUtility.getString(request.getParameter("password")));

        log.debug("LOginCtl Method PopulatedBean End");

        return bean;
    }

    /**
     * Display Login form
     * 
     */
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        log.debug("Method doGet Started");
        
        
        HttpSession session = request.getSession(true);
        String op = DataUtility.getString(request.getParameter("operation"));
        
        UserModel model = new UserModel();
        
        long id = DataUtility.getLong(request.getParameter("id"));

        if (id > 0) {
            UserBean userBean;
            try {
                userBean = model.findByPK(id);
                ServletUtility.setBean(userBean, request);
        
            } catch (Exception e) {
                log.error(e);
                ServletUtility.handleException(e, request, response);
                return;
            }
        } else if (OP_LOG_OUT.equals(op)) {
            session = request.getSession(false);
            session.invalidate();
            ServletUtility.setSuccessMessage("You have been logged out successfully", request);
            
            ServletUtility.forward(TMSView.LOGIN_VIEW, request, response);
            return;
        }
        if (session.getAttribute("user") != null) {
            ServletUtility.redirect(TMSView.WELCOME_CTL, request, response);
            return;
        }
        ServletUtility.forward(getView(), request, response);
        log.debug("Method doGet end");
    }

    /**
     * Submit Logic
     */

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        
        
        log.debug(" LoginCtl Method doPost Started");
        
        HttpSession session = request.getSession(true);
        
        String op = DataUtility.getString(request.getParameter("operation"));
        // get Model
        UserModel model = new UserModel();
        
        long id = DataUtility.getLong(request.getParameter("id"));
        
        
        if (OP_SIGN_IN.equalsIgnoreCase(op)) {
            UserBean bean = (UserBean) populateBean(request);
            try {
                bean = model.authenticate(bean.getLogin(), bean.getPassword());
                
                if (bean != null) {
                    session.setAttribute("user", bean);
                    session.setMaxInactiveInterval(10 * 6000);

                    long rollId = bean.getRoleId();
                    String uri = request.getParameter("uri");
                    
                    if (uri == null || "null".equalsIgnoreCase(uri)) {
                        if(bean.getRoleId()==1) {
                        ServletUtility.redirect(TMSView.WELCOME_CTL, request, response);
                        }else {
                            ServletUtility.redirect(TMSView.USER_PACKAGE_CTL, request, response);
                        }
                        return;
                    } else {
                        ServletUtility.redirect(uri, request, response);
                    }
                    return;
                } else {
                    bean = (UserBean) populateBean(request);
                    ServletUtility.setBean(bean, request);
                    ServletUtility.setErrorMessage("Invalid LoginId And Password", request);
                }

            } catch (ApplicationException e) {
                log.error(e);
                ServletUtility.handleException(e, request, response);
                
                return;
            }
        } else if (OP_SIGN_UP.equalsIgnoreCase(op)) {
            ServletUtility.redirect(TMSView.USER_REGISTRATION_CTL, request, response);
        return;
        }
        ServletUtility.forward(getView(), request, response);
        log.debug("UserCtl Method doPost Ended");
    }

    /**
     * Returns the VIEW page of this Controller
     * 
     * @return
     */
    protected String getView() {
        return TMSView.LOGIN_VIEW;
    }

}

Model

Models are the Java Classes that come under the model package, that contains, database transactions like ADD Data, Edit Data, Delete Data, etc.

As standard development, we keep all the database-related methods under the model packages. it’s a separate package so in case if we need to update or make any changes from the backend we can update the only models.

Role of models

  • Create a connection with the database.
  • Get the data from the database.
  • Enter the data into the database.
  • Update records.

Sample code for User Model(UserModel.java)

package com.tourism.mgt.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.tourism.mgt.bean.UserBean;
import com.tourism.mgt.exception.ApplicationException;
import com.tourism.mgt.exception.DatabaseException;
import com.tourism.mgt.exception.DuplicateRecordException;
import com.tourism.mgt.exception.RecordNotFoundException;
import com.tourism.mgt.util.DataUtility;
import com.tourism.mgt.util.EmailBuilder;
import com.tourism.mgt.util.EmailMessage;
import com.tourism.mgt.util.EmailUtility;
import com.tourism.mgt.util.JDBCDataSource;


public class UserModel {
    private static Logger log = Logger.getLogger(UserModel.class);
    

    public Integer nextPK() throws DatabaseException {
        log.debug("Model nextPK Started");
        Connection conn = null;
        int pk = 0;

        try {
            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT MAX(ID) FROM T_USER");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                pk = rs.getInt(1);
            }
            rs.close();

        } catch (Exception e) {
            log.error("Database Exception..", e);
            throw new DatabaseException("Exception : Exception in getting PK");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        log.debug("Model nextPK End");
        return pk + 1;
    }

    /**
     * Add a User
     * 
     * @param bean
     * @throws DatabaseException
     * 
     */
    public long add(UserBean bean) throws ApplicationException, DuplicateRecordException {
        
        Connection conn = null;
        int pk = 0;

        UserBean existbean = findByLogin(bean.getLogin());

        if (existbean != null) {
            throw new DuplicateRecordException("Login Id already exists");
        }

        try {
            conn = JDBCDataSource.getConnection();
            pk = nextPK();
            conn.setAutoCommit(false); // Begin transaction
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO T_USER VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
            pstmt.setInt(1, pk);
            pstmt.setString(2, bean.getFirstName());
            pstmt.setString(3, bean.getLastName());
            pstmt.setString(4, bean.getLogin());
            pstmt.setString(5, bean.getPassword());
            pstmt.setString(6, bean.getMobileNo());
            pstmt.setDate(7, new java.sql.Date(bean.getDob().getTime()));
            pstmt.setString(8, bean.getGender());
            pstmt.setLong(9, bean.getRoleId());
            pstmt.setString(10, bean.getCreatedBy());
            pstmt.setString(11, bean.getModifiedBy());
            pstmt.setTimestamp(12, bean.getCreatedDatetime());
            pstmt.setTimestamp(13, bean.getModifiedDatetime());
            pstmt.executeUpdate();
            conn.commit(); // End transaction
            pstmt.close();
        } catch (Exception e) {
        
            try {
                conn.rollback();
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new ApplicationException("Exception : add rollback exception " + ex.getMessage());
            }
            throw new ApplicationException("Exception : Exception in add User");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        
        return pk;
    }

    
    public void delete(UserBean bean) throws ApplicationException {
        
        Connection conn = null;
        try {
            conn = JDBCDataSource.getConnection();
            conn.setAutoCommit(false); // Begin transaction
            PreparedStatement pstmt = conn.prepareStatement("DELETE FROM T_USER WHERE ID=?");
            pstmt.setLong(1, bean.getId());
            pstmt.executeUpdate();
            conn.commit(); // End transaction
            pstmt.close();

        } catch (Exception e) {
        
            try {
                conn.rollback();
            } catch (Exception ex) {
                throw new ApplicationException("Exception : Delete rollback exception " + ex.getMessage());
            }
            throw new ApplicationException("Exception : Exception in delete User");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        
    }

    public UserBean findByLogin(String login) throws ApplicationException {
        log.debug("Model findByLogin Started");
        StringBuffer sql = new StringBuffer("SELECT * FROM T_USER WHERE LOGIN=?");
        UserBean bean = null;
        Connection conn = null;
        System.out.println("sql" + sql);

        try {
            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
            pstmt.setString(1, login);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                bean = new UserBean();
                bean.setId(rs.getLong(1));
                bean.setFirstName(rs.getString(2));
                bean.setLastName(rs.getString(3));
                bean.setLogin(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setMobileNo(rs.getString(6));
                bean.setDob(rs.getDate(7));
                bean.setRoleId(rs.getLong(8));
                bean.setGender(rs.getString(9));
                bean.setCreatedBy(rs.getString(10));
                bean.setModifiedBy(rs.getString(11));
                bean.setCreatedDatetime(rs.getTimestamp(12));
                bean.setModifiedDatetime(rs.getTimestamp(13));

            }
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Database Exception..", e);
            throw new ApplicationException("Exception : Exception in getting User by login");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        log.debug("Model findByLogin End");
        return bean;
    }

    

    public UserBean findByPK(long pk) throws ApplicationException {
        log.debug("Model findByPK Started");
        StringBuffer sql = new StringBuffer("SELECT * FROM T_USER WHERE ID=?");
        UserBean bean = null;
        Connection conn = null;

        try {
            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
            pstmt.setLong(1, pk);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                bean = new UserBean();
                bean.setId(rs.getLong(1));
                bean.setFirstName(rs.getString(2));
                bean.setLastName(rs.getString(3));
                bean.setLogin(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setMobileNo(rs.getString(6));
                bean.setDob(rs.getDate(7));
                bean.setGender(rs.getString(8));
                bean.setRoleId(rs.getLong(9));
                bean.setCreatedBy(rs.getString(10));
                bean.setModifiedBy(rs.getString(11));
                bean.setCreatedDatetime(rs.getTimestamp(12));
                bean.setModifiedDatetime(rs.getTimestamp(13));

            }
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Database Exception..", e);
            throw new ApplicationException("Exception : Exception in getting User by pk");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        log.debug("Model findByPK End");
        return bean;
    }

    

    public void update(UserBean bean) throws ApplicationException, DuplicateRecordException {
        log.debug("Model update Started");
        Connection conn = null;

        UserBean beanExist = findByLogin(bean.getLogin());
        // Check if updated LoginId already exist
        if (beanExist != null && !(beanExist.getId() == bean.getId())) {
            throw new DuplicateRecordException("LoginId is already exist");
        }

        try {
            conn = JDBCDataSource.getConnection();
            conn.setAutoCommit(false); // Begin transaction
            PreparedStatement pstmt = conn.prepareStatement(
                    "UPDATE T_USER SET FIRST_NAME=?,LAST_NAME=?,LOGIN=?,PASSWORD=?,MOBILE_NO=?,DOB=?,GENDER=?,ROLE_ID=?,"
                    + "CREATED_BY=?,MODIFIED_BY=?,CREATED_DATETIME=?,MODIFIED_DATETIME=? WHERE ID=?");
            pstmt.setString(1, bean.getFirstName());
            pstmt.setString(2, bean.getLastName());
            pstmt.setString(3, bean.getLogin());
            pstmt.setString(4, bean.getPassword());
            pstmt.setString(5, bean.getMobileNo());
            pstmt.setDate(6, new java.sql.Date(bean.getDob().getTime()));
            pstmt.setString(7, bean.getGender());
            pstmt.setLong(8, bean.getRoleId());
            pstmt.setString(9, bean.getCreatedBy());
            pstmt.setString(10, bean.getModifiedBy());
            pstmt.setTimestamp(11, bean.getCreatedDatetime());
            pstmt.setTimestamp(12, bean.getModifiedDatetime());
            pstmt.setLong(13, bean.getId());
            pstmt.executeUpdate();
            conn.commit(); // End transaction
            pstmt.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Database Exception..", e);
            try {
                conn.rollback();
            } catch (Exception ex) {
                throw new ApplicationException("Exception : Delete rollback exception " + ex.getMessage());
            }
            throw new ApplicationException("Exception in updating User ");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        log.debug("Model update End");
    }

    

    public List search(UserBean bean) throws ApplicationException {
        return search(bean, 0, 0);
    }

    

    public List search(UserBean bean, int pageNo, int pageSize) throws ApplicationException {
        log.debug("Model search Started");
        StringBuffer sql = new StringBuffer("SELECT * FROM T_USER WHERE 1=1");

        if (bean != null) {
            if (bean.getId() > 0) {
                sql.append(" AND id = " + bean.getId());
            }
            if (bean.getFirstName() != null && bean.getFirstName().length() > 0) {
                sql.append(" AND FIRST_NAME like '" + bean.getFirstName() + "%'");
            }
            if (bean.getLastName() != null && bean.getLastName().length() > 0) {
                sql.append(" AND LAST_NAME like '" + bean.getLastName() + "%'");
            }
            if (bean.getLogin() != null && bean.getLogin().length() > 0) {
                sql.append(" AND LOGIN like '" + bean.getLogin() + "%'");
            }
            if (bean.getPassword() != null && bean.getPassword().length() > 0) {
                sql.append(" AND PASSWORD like '" + bean.getPassword() + "%'");
            }
            if (bean.getDob() != null && bean.getDob().getDate() > 0) {
                sql.append(" AND DOB = " + bean.getGender());
            }
            if (bean.getMobileNo() != null && bean.getMobileNo().length() > 0) {
                sql.append(" AND MOBILE_NO = " + bean.getMobileNo());
            }
            if (bean.getRoleId() > 0) {
                sql.append(" AND ROLE_ID = " + bean.getRoleId());
            }
        }
        if (pageSize > 0) {
            pageNo = (pageNo - 1) * pageSize;
            sql.append(" Limit " + pageNo + ", " + pageSize);
        }
        ArrayList list = new ArrayList();
        Connection conn = null;
        try {
            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                bean = new UserBean();
                bean.setId(rs.getLong(1));
                bean.setFirstName(rs.getString(2));
                bean.setLastName(rs.getString(3));
                bean.setLogin(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setMobileNo(rs.getString(6));
                bean.setDob(rs.getDate(7));
                bean.setGender(rs.getString(8));
                bean.setRoleId(rs.getLong(9));
                bean.setCreatedBy(rs.getString(10));
                bean.setModifiedBy(rs.getString(11));
                bean.setCreatedDatetime(rs.getTimestamp(12));
                bean.setModifiedDatetime(rs.getTimestamp(13));

                list.add(bean);
            }
            rs.close();
        } catch (Exception e) {
            log.error("Database Exception..", e);
            throw new ApplicationException("Exception : Exception in search user");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }

        log.debug("Model search End");
        return list;
    }

    

    public List list() throws ApplicationException {
        return list(0, 0);
    }


    public List list(int pageNo, int pageSize) throws ApplicationException {
        log.debug("Model list Started");
        ArrayList list = new ArrayList();
        StringBuffer sql = new StringBuffer("select * from T_USER");
        // if page size is greater than zero then apply pagination
        if (pageSize > 0) {
            // Calculate start record index
            pageNo = (pageNo - 1) * pageSize;
            sql.append(" limit " + pageNo + "," + pageSize);
        }

        
        System.out.println("sql in list user :"+sql);
        Connection conn = null;

        try {
            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                UserBean bean = new UserBean();
                bean.setId(rs.getLong(1));
                bean.setFirstName(rs.getString(2));
                bean.setLastName(rs.getString(3));
                bean.setLogin(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setMobileNo(rs.getString(6));
                bean.setDob(rs.getDate(7));
                bean.setGender(rs.getString(8));
                bean.setRoleId(rs.getLong(9));
                bean.setCreatedBy(rs.getString(10));
                bean.setModifiedBy(rs.getString(11));
                bean.setCreatedDatetime(rs.getTimestamp(12));
                bean.setModifiedDatetime(rs.getTimestamp(13));

                list.add(bean);
            }
            rs.close();
        } catch (Exception e) {
            log.error("Database Exception..", e);
            throw new ApplicationException("Exception : Exception in getting list of users");
        } finally {
            JDBCDataSource.closeConnection(conn);
        }

        log.debug("Model list End");
        return list;

    }

    

    public UserBean authenticate(String login, String password) throws ApplicationException {
        log.debug("Model authenticate Started");
        StringBuffer sql = new StringBuffer("SELECT * FROM T_USER WHERE LOGIN = ? AND PASSWORD = ?");
        UserBean bean = null;
        Connection conn = null;

        try {
            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
            pstmt.setString(1, login);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                bean = new UserBean();
                bean.setId(rs.getLong(1));
                bean.setFirstName(rs.getString(2));
                bean.setLastName(rs.getString(3));
                bean.setLogin(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setMobileNo(rs.getString(6));
                bean.setDob(rs.getDate(7));
                bean.setGender(rs.getString(8));
                bean.setRoleId(rs.getLong(9));
                bean.setCreatedBy(rs.getString(10));
                bean.setModifiedBy(rs.getString(11));
                bean.setCreatedDatetime(rs.getTimestamp(12));
                bean.setModifiedDatetime(rs.getTimestamp(13));
            }
        } catch (Exception e) {
            log.error("Database Exception..", e);
            throw new ApplicationException("Exception : Exception in get roles");

        } finally { 
            JDBCDataSource.closeConnection(conn);
        }

        log.debug("Model authenticate End");
        return bean;
    }

    



    
    public List getRoles(UserBean bean) throws ApplicationException {
        log.debug("Model get roles Started");
        StringBuffer sql = new StringBuffer("SELECT * FROM T_USER WHERE role_Id=?");
        Connection conn = null;
        List list = new ArrayList();
        try {

            conn = JDBCDataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
            pstmt.setLong(1, bean.getRoleId());
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                bean = new UserBean();
                bean.setId(rs.getLong(1));
                bean.setFirstName(rs.getString(2));
                bean.setLastName(rs.getString(3));
                bean.setLogin(rs.getString(4));
                bean.setPassword(rs.getString(5));
                bean.setMobileNo(rs.getString(6));
                bean.setDob(rs.getDate(7));
                bean.setGender(rs.getString(8));
                bean.setRoleId(rs.getLong(9));
                bean.setCreatedBy(rs.getString(10));
                bean.setModifiedBy(rs.getString(11));
                bean.setCreatedDatetime(rs.getTimestamp(12));
                bean.setModifiedDatetime(rs.getTimestamp(13));

                list.add(bean);
            }
            rs.close();
        } catch (Exception e) {
            log.error("Database Exception..", e);
            throw new ApplicationException("Exception : Exception in get roles");

        } finally {
            JDBCDataSource.closeConnection(conn);
        }
        log.debug("Model get roles End");
        return list;
    }

    

        public boolean changePassword(Long id, String oldPassword, String newPassword)
                throws RecordNotFoundException, ApplicationException {

            log.debug("model changePassword Started");
            
            boolean flag = false;
            
            UserBean beanExist = null;

            beanExist = findByPK(id);
            
            if (beanExist != null && beanExist.getPassword().equals(oldPassword)) {
                beanExist.setPassword(newPassword);
                try {
                    update(beanExist);
                } catch (DuplicateRecordException e) {
                    log.error(e);
                    throw new ApplicationException("LoginId is already exist");
                }
                flag = true;
            } else {
                throw new RecordNotFoundException("Old password is Invalid");
            }

            HashMap<String, String> map = new HashMap<String, String>();

            map.put("login", beanExist.getLogin());
            map.put("password", beanExist.getPassword());
            map.put("firstName", beanExist.getFirstName());
            map.put("lastName", beanExist.getLastName());

            String message = EmailBuilder.getChangePasswordMessage(map);

            EmailMessage msg = new EmailMessage();

            msg.setTo(beanExist.getLogin());
            msg.setSubject("SUNARYS ORS Password has been changed Successfully.");
            msg.setMessage(message);
            msg.setMessageType(EmailMessage.HTML_MSG);

            try {
                EmailUtility.sendMail(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }

            log.debug("Model changePassword End");
            return flag;

        }

    public UserBean updateAccess(UserBean bean) throws ApplicationException {
        return null;
    }

    public long registerUser(UserBean bean)
            throws ApplicationException, DuplicateRecordException {

        log.debug("Model add Started");

        long pk = add(bean);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("login", bean.getLogin());
        map.put("password", bean.getPassword());

        String message = EmailBuilder.getUserRegistrationMessage(map);

        EmailMessage msg = new EmailMessage();

        msg.setTo(bean.getLogin());
        msg.setSubject("Registration is successful for Online Tourism System");
        msg.setMessage(message);
        msg.setMessageType(EmailMessage.HTML_MSG);

        try {
            EmailUtility.sendMail(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return pk;
    }
    

    public boolean forgetPassword(String login)
            throws ApplicationException, RecordNotFoundException, ApplicationException {
        UserBean userData = findByLogin(login);
        
        boolean flag = false;

        if (userData == null) {
            throw new RecordNotFoundException("Email ID does not exists !");

        }

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("login", userData.getLogin());
        map.put("password", userData.getPassword());
        map.put("firstName", userData.getFirstName());
        map.put("lastName", userData.getLastName());
        String message = EmailBuilder.getForgetPasswordMessage(map);
        EmailMessage msg = new EmailMessage();
        msg.setTo(login);
        msg.setSubject("Online Tourism System Password reset");
        msg.setMessage(message);
        msg.setMessageType(EmailMessage.HTML_MSG);
        EmailUtility.sendMail(msg);
        flag = true;

        return flag;
    }
}