Library management system project in java with source code

Library management system project in java with source code and project report. Library management project in java is a web application using JSP, Servlet, MYSQL, and eclipse.

Library management is a web-based Java application that automates the working of a library or book center that manages and maintains records of the books in the book library.

Library management system project i...
Library management system project in java

The librarian holds various activities like adding new books, Viewing all the books, Adding a new student in the system managing the book records ETC.

Objective of library management

The objective of the library management system is to design a web application in java that can manage a library. An easy and user-friendly interface that is easy to operate and understand for the students as well as for librarians.  An Easy platform to manage books and the records of books like the issued book and the student records.

The Library management system in java is developed using JSP and servlets. It uses MYSQL to manage the backend activities. This java project is using maven to manage the dependencies and follows MVC architecture to manage the project resources.

It uses a tomcat server for deployment and we can use eclipse, STS, or Netbeans as IDE to run this project.

Let’s understand the features and functionalities of the library management system in detail according to the module and application actors.

So there are two main actors of the application Admin and User.

1)Admin(librarian):

The librarian can Add/edit/update the record of students.

The librarian can Add/edit/update the record of Books.

The librarian can Search Books.

The librarian can Search Students.

The librarian can Issue books and library cards.

2)User(Student):

A student can register in the system

A student can view his profile(Edit/Update).

A student can check the history of issuing books.

Technologies and Platform

Library management software is being designed and developed on an Open Platform i.e. J2EE. MYSQL will be used to maintain the database. To achieve a high degree of modularity, scalability, and maintainability, it is recommended to adopt n- tier architecture while designing the Library management System.

Accordingly, it is proposed that the entire application development logic, database logic, and presentation logic shall be segregated. It is proposed that the LMS software package shall be running on Apache Tomcat Web Server. The Web Server will be responsible for rendering the JSP pages and the result is shown back to the end-user.

Hardware requirements

  • 4 GB of RAM with 20GB HDD.

Software requirements

  •  OS platform which supports JDK(Java) Like windows, mac, or Linux.
  • JDK 1.8
  • Eclipse/STS/Netbeans.
  • MYSQL v5.6 or above.
  • Tomcat 8.5 or above.

Contact to download source code and configuration

Skype Id: jcodebun
Email: jcodebun@gmail.com
WhatsApp: +91 8827363777

Price: 1500 INR

Library Management Project Source code in Java

Here are some sample Source code and Application architecture. Below is the source code for the complete source code of the user module of the library management project in Java.

UserList.view

<%@page import="in.co.lib.mgt.model.UserModel"%>
<%@page import="in.co.lib.mgt.util.DataUtility"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="in.co.lib.mgt.util.ServletUtility"%>
<%@page import="in.co.lib.mgt.controller.UserListCtl"%>


<%@ 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>User List </title>
</head>
<body>
<%@ include file="Header.jsp" %>
<div style="width: 100%;background-color: #04091e;height: 69px; padding: 19px ;margin-top: 68px" >
<h2 style="color: white; font-family:inherit;">User List</h2></div>
<br><br>
<form action="<%=LIBView.USER_LIST_CTL%>" method="post">
<div class="container">
 <div class="col-lg-12 well">
 <div class="row">
     <div class="col-sm-12">
     <div class="row">
       <div class="col-sm-3 form-group">
        <input type="text" placeholder="Enter  Name Here.." name="firstName" class="form-control" >
       </div>
       <div class="col-sm-3 form-group">
        <input type="text" placeholder="Enter Library Code Here.." name="code" class="form-control" >
       </div>
       
       <div class="col-sm-3 form-group">
        
        <input type="submit"
                       			 name="operation" class="btn btn-md btn-info" value="<%=UserListCtl.OP_SEARCH%>" >
       </div>
      </div>					
   </div>		
  </div>
 </div>
</div>
<b><font color="red"> <%=ServletUtility.getErrorMessage(request)%>
         </font></b> <b><font color="Green"> <%=ServletUtility.getSuccessMessage(request)%>
         </font></b>
<table class="table">
   <thead class="thead-dark">
    <tr>
     <th scope="col">S.No.</th>
     <th scope="col">Library Code</th>
     <th scope="col">Name</th>
     <th scope="col">Email Id</th>
     <th scope="col">Date Of Birth</th>
     <th scope="col">Contect No.</th>
    
    </tr>
   </thead>
    <%
    int pageNo = ServletUtility.getPageNo(request);
    int pageSize = ServletUtility.getPageSize(request);
    int index = ((pageNo - 1) * pageSize) + 1;
    UserBean bean = null;
    List list = ServletUtility.getList(request);
    Iterator<UserBean> i = list.iterator();
    while (i.hasNext()) {
     bean = i.next();
    %> 
   <tbody>
    <tr>
     <th scope="row"><%=index++%></th>
     <td><%=bean.getLibraryCode()%></td>
     <td><%=bean.getFirstName()+" "+bean.getLastName()%></td>
     <td><%=bean.getEmailId()%></td>
     <td><%=DataUtility.getDateString(bean.getDob())%>
     <td><%=bean.getMobileNo()%></td>
     </tr>
     <%} %>
    
    
   </tbody>
  </table>
  
  <table width="99%">
    <tr>
     <td><input type="submit" name="operation" class="btn btn-success"
      value="<%=UserListCtl.OP_PREVIOUS%>"
      <%=(pageNo == 1) ? "disabled" : ""%>></td>

    
     <%
      UserModel model = new UserModel();
     %>
     <td align="right"><input type="submit" name="operation" class="btn btn-success"
      value="<%=UserListCtl.OP_NEXT%>"
      <%=((list.size() < pageSize) || model.nextPK() - 1 == bean.getId()) ? "disabled" : ""%>></td>

    </tr>
   </table>
  
  <input type="hidden" name="pageNo" value="<%=pageNo%>"> <input
    type="hidden" name="pageSize" value="<%=pageSize%>">
 </form>
<br><br><br>
 <%@ include file="Footer.jsp"%>
</body>
</html>

UserBean.java

<%@page import="in.co.lib.mgt.model.UserModel"%>
<%@page import="in.co.lib.mgt.util.DataUtility"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="in.co.lib.mgt.util.ServletUtility"%>
<%@page import="in.co.lib.mgt.controller.UserListCtl"%>


<%@ 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>User List </title>
</head>
<body>
<%@ include file="Header.jsp" %>
<div style="width: 100%;background-color: #04091e;height: 69px; padding: 19px ;margin-top: 68px" >
<h2 style="color: white; font-family:inherit;">User List</h2></div>
<br><br>
<form action="<%=LIBView.USER_LIST_CTL%>" method="post">
<div class="container">
 <div class="col-lg-12 well">
 <div class="row">
     <div class="col-sm-12">
     <div class="row">
       <div class="col-sm-3 form-group">
        <input type="text" placeholder="Enter  Name Here.." name="firstName" class="form-control" >
       </div>
       <div class="col-sm-3 form-group">
        <input type="text" placeholder="Enter Library Code Here.." name="code" class="form-control" >
       </div>
       
       <div class="col-sm-3 form-group">
        
        <input type="submit"
                       			 name="operation" class="btn btn-md btn-info" value="<%=UserListCtl.OP_SEARCH%>" >
       </div>
      </div>					
   </div>		
  </div>
 </div>
</div>
<b><font color="red"> <%=ServletUtility.getErrorMessage(request)%>
         </font></b> <b><font color="Green"> <%=ServletUtility.getSuccessMessage(request)%>
         </font></b>
<table class="table">
   <thead class="thead-dark">
    <tr>
     <th scope="col">S.No.</th>
     <th scope="col">Library Code</th>
     <th scope="col">Name</th>
     <th scope="col">Email Id</th>
     <th scope="col">Date Of Birth</th>
     <th scope="col">Contect No.</th>
    
    </tr>
   </thead>
    <%
    int pageNo = ServletUtility.getPageNo(request);
    int pageSize = ServletUtility.getPageSize(request);
    int index = ((pageNo - 1) * pageSize) + 1;
    UserBean bean = null;
    List list = ServletUtility.getList(request);
    Iterator<UserBean> i = list.iterator();
    while (i.hasNext()) {
     bean = i.next();
    %> 
   <tbody>
    <tr>
     <th scope="row"><%=index++%></th>
     <td><%=bean.getLibraryCode()%></td>
     <td><%=bean.getFirstName()+" "+bean.getLastName()%></td>
     <td><%=bean.getEmailId()%></td>
     <td><%=DataUtility.getDateString(bean.getDob())%>
     <td><%=bean.getMobileNo()%></td>
     </tr>
     <%} %>
    
    
   </tbody>
  </table>
  
  <table width="99%">
    <tr>
     <td><input type="submit" name="operation" class="btn btn-success"
      value="<%=UserListCtl.OP_PREVIOUS%>"
      <%=(pageNo == 1) ? "disabled" : ""%>></td>

    
     <%
      UserModel model = new UserModel();
     %>
     <td align="right"><input type="submit" name="operation" class="btn btn-success"
      value="<%=UserListCtl.OP_NEXT%>"
      <%=((list.size() < pageSize) || model.nextPK() - 1 == bean.getId()) ? "disabled" : ""%>></td>

    </tr>
   </table>
  
  <input type="hidden" name="pageNo" value="<%=pageNo%>"> <input
    type="hidden" name="pageSize" value="<%=pageSize%>">
 </form>
<br><br><br>
 <%@ include file="Footer.jsp"%>
</body>
</html>

UserList Controller(Servlet)

package in.co.lib.mgt.controller;

import java.io.IOException;
import java.util.List;

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 org.apache.log4j.Logger;

import in.co.lib.mgt.bean.BaseBean;
import in.co.lib.mgt.bean.UserBean;
import in.co.lib.mgt.exception.ApplicationException;
import in.co.lib.mgt.model.UserModel;
import in.co.lib.mgt.util.DataUtility;
import in.co.lib.mgt.util.PropertyReader;
import in.co.lib.mgt.util.ServletUtility;



/**
 * Servlet implementation class UserListCtl
 */

/**
 *
 * @author Navigable set
 * @version 1.0
 * @Copyright (c) Navigable Set
 *
 */
@WebServlet(name = "UserListCtl", urlPatterns = { "/ctl/UserListCtl" })
public class UserListCtl extends BaseCtl {
 private static Logger log = Logger.getLogger(UserListCtl.class);

 /**
  * Populates bean object from request parameters
  * 
  * @param request
  * @return
  */
 @Override
 protected BaseBean populateBean(HttpServletRequest request) {
  log.debug("UserListCtl populateBean method start");
  UserBean bean = new UserBean();

  bean.setFirstName(DataUtility.getString(request.getParameter("firstName")));

  bean.setLastName(DataUtility.getString(request.getParameter("lastName")));

  bean.setLogin(DataUtility.getString(request.getParameter("login")));
  bean.setLibraryCode(DataUtility.getLong(request.getParameter("code")));
  log.debug("UserListCtl populateBean method end");
  return bean;
 }

 /**
  * Contains Display logics
  */

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  log.debug("UserListCtl doGet Start");
  List list = null;

  int pageNo = 1;

  int pageSize = DataUtility.getInt(PropertyReader.getValue("page.size"));

  UserBean bean = (UserBean) populateBean(request);

  String op = DataUtility.getString(request.getParameter("operation"));
  // get the selected checkbox ids array for delete list

  String[] ids = request.getParameterValues("ids");

  UserModel model = new UserModel();
  try {

   list = model.search(bean, pageNo, pageSize);

   
  
   if (list == null || list.size() == 0) {
    ServletUtility.setErrorMessage("No record found ", request);
   }

   ServletUtility.setList(list, request);
   ServletUtility.setPageNo(pageNo, request);
   ServletUtility.setPageSize(pageSize, request);
   ServletUtility.forward(getView(), request, response);
  } catch (ApplicationException e) {
   log.error(e);
   ServletUtility.handleException(e, request, response);
   return;
  }
  log.debug("UserListCtl doPOst End");
 }

 /**
  * Contains Submit logics
  */
 @Override

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  log.debug("UserListCtl doPost Start");
  
  
  List list = null;
  int pageNo = DataUtility.getInt(request.getParameter("pageNo"));
  int pageSize = DataUtility.getInt(request.getParameter("pageSize"));

  pageNo = (pageNo == 0) ? 1 : pageNo;
  pageSize = (pageSize == 0) ? DataUtility.getInt(PropertyReader.getValue("page.size")) : pageSize;
  
  UserBean bean = (UserBean) populateBean(request);
  
  String op = DataUtility.getString(request.getParameter("operation"));
  // get the selected checkbox ids array for delete list
  
  String[] ids = request.getParameterValues("ids");
  
  UserModel model = new UserModel();
  try {

   if (OP_SEARCH.equalsIgnoreCase(op) || "Next".equalsIgnoreCase(op) || "Previous".equalsIgnoreCase(op)) {

    if (OP_SEARCH.equalsIgnoreCase(op)) {
     pageNo = 1;
    } else if (OP_NEXT.equalsIgnoreCase(op)) {
     pageNo++;
    } else if (OP_PREVIOUS.equalsIgnoreCase(op) && pageNo > 1) {
     pageNo--;
    }

   } else if (OP_NEW.equalsIgnoreCase(op)) {
    ServletUtility.redirect(LIBView.USER_CTL, request, response);
    return;
   } else if (OP_DELETE.equalsIgnoreCase(op)) {
    pageNo = 1;
    if (ids != null && ids.length > 0) {
     UserBean deletebean = new UserBean();
     for (String id : ids) {
      deletebean.setId(DataUtility.getInt(id));
      model.delete(deletebean);
     }
     ServletUtility.setSuccessMessage("Data Deleted Successfully", request);
    } else {
     ServletUtility.setErrorMessage("Select at least one record", request);
    }
   } else if (OP_RESET.equalsIgnoreCase(op)) {
    ServletUtility.redirect(LIBView.USER_LIST_CTL, request, response);
    return;

   }

   list = model.search(bean, pageNo, pageSize);
   
   
   if (list == null || list.size() == 0) {
    ServletUtility.setErrorMessage("No record found ", request);
   }
   ServletUtility.setList(list, request);
   ServletUtility.setPageNo(pageNo, request);
   ServletUtility.setPageSize(pageSize, request);
   ServletUtility.forward(getView(), request, response);

  } catch (ApplicationException e) {
   log.error(e);
   ServletUtility.handleException(e, request, response);
   return;
  }
  log.debug("UserListCtl doGet End");

 }

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

UserModel

package in.co.lib.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 in.co.lib.mgt.bean.UserBean;
import in.co.lib.mgt.exception.ApplicationException;
import in.co.lib.mgt.exception.DatabaseException;
import in.co.lib.mgt.exception.DuplicateRecordException;
import in.co.lib.mgt.exception.RecordNotFoundException;
import in.co.lib.mgt.util.EmailBuilder;
import in.co.lib.mgt.util.EmailMessage;
import in.co.lib.mgt.util.EmailUtility;
import in.co.lib.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 LI_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;
 }
 
 public Integer nextLibCode() throws DatabaseException {
  log.debug("Model nextPK Started");
  Connection conn = null;
  int pk = 0;

  try {
   conn = JDBCDataSource.getConnection();
   PreparedStatement pstmt = conn.prepareStatement("SELECT MAX(LibraryCode) FROM LI_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;
 }
 
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();
   // Get auto-generated next primary key
   System.out.println(pk + " in ModelJDBC");
   conn.setAutoCommit(false); // Begin transaction
   PreparedStatement pstmt = conn.prepareStatement("INSERT INTO LI_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.setDate(6, new java.sql.Date(bean.getDob().getTime()));
   pstmt.setString(7, bean.getMobileNo());
   pstmt.setLong(8,nextLibCode());
   pstmt.setString(9,bean.getEmailId());
   pstmt.setString(10, bean.getGender());
   pstmt.setLong(11, bean.getRoleId());
   pstmt.setString(12, bean.getCreatedBy());
   pstmt.setString(13, bean.getModifiedBy());
   pstmt.setTimestamp(14, bean.getCreatedDatetime());
   pstmt.setTimestamp(15, 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 UserBean findByLogin(String login) throws ApplicationException {
  log.debug("Model findByLogin Started");
  StringBuffer sql = new StringBuffer("SELECT * FROM LI_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.setDob(rs.getDate(6));
    bean.setMobileNo(rs.getString(7));
    bean.setLibraryCode(rs.getLong(8));
    bean.setEmailId(rs.getString(9));
    bean.setGender(rs.getString(10));
    bean.setRoleId(rs.getLong(11));
    bean.setCreatedBy(rs.getString(12));
    bean.setModifiedBy(rs.getString(13));
    bean.setCreatedDatetime(rs.getTimestamp(14));
    bean.setModifiedDatetime(rs.getTimestamp(15));
   }
   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 LI_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.setDob(rs.getDate(6));
    bean.setMobileNo(rs.getString(7));
    bean.setLibraryCode(rs.getLong(8));
    bean.setEmailId(rs.getString(9));
    bean.setGender(rs.getString(10));
    bean.setRoleId(rs.getLong(11));
    bean.setCreatedBy(rs.getString(12));
    bean.setModifiedBy(rs.getString(13));
    bean.setCreatedDatetime(rs.getTimestamp(14));
    bean.setModifiedDatetime(rs.getTimestamp(15));

   }
   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 UserBean findByLibCode(long code) throws ApplicationException {
  log.debug("Model findByPK Started");
  StringBuffer sql = new StringBuffer("SELECT * FROM LI_USER WHERE LibraryCode=?");
  UserBean bean = null;
  Connection conn = null;

  try {
   conn = JDBCDataSource.getConnection();
   PreparedStatement pstmt = conn.prepareStatement(sql.toString());
   pstmt.setLong(1, code);
   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.setDob(rs.getDate(6));
    bean.setMobileNo(rs.getString(7));
    bean.setLibraryCode(rs.getLong(8));
    bean.setEmailId(rs.getString(9));
    bean.setGender(rs.getString(10));
    bean.setRoleId(rs.getLong(11));
    bean.setCreatedBy(rs.getString(12));
    bean.setModifiedBy(rs.getString(13));
    bean.setCreatedDatetime(rs.getTimestamp(14));
    bean.setModifiedDatetime(rs.getTimestamp(15));

   }
   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 UserBean authenticate(String login, String password) throws ApplicationException {
  log.debug("Model authenticate Started");
  StringBuffer sql = new StringBuffer("SELECT * FROM LI_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.setDob(rs.getDate(6));
    bean.setMobileNo(rs.getString(7));
    bean.setLibraryCode(rs.getLong(8));
    bean.setEmailId(rs.getString(9));
    bean.setGender(rs.getString(10));
    bean.setRoleId(rs.getLong(11));
    bean.setCreatedBy(rs.getString(12));
    bean.setModifiedBy(rs.getString(13));
    bean.setCreatedDatetime(rs.getTimestamp(14));
    bean.setModifiedDatetime(rs.getTimestamp(15));
    System.out.println("Usermodel here");
   }
  } 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 long registerUser(UserBean bean)
   throws ApplicationException, DuplicateRecordException {

  log.debug("Model add Started");

  long pk = add(bean);

  return pk;
 }
 
 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 LI_USER SET FirstNAME=?,LastNAME=?,LOGIN=?,PASSWORD=?,DOB=?,MOBILENO=?,librarycode=?,emailId=?,GENDER=?,ROLEID=?,"
    + "CREATEDBY=?,MODIFIEDBY=?,CREATEDDATETIME=?,MODIFIEDDATETIME=? WHERE ID=?");
  pstmt.setString(1, bean.getFirstName());
  pstmt.setString(2, bean.getLastName());
  pstmt.setString(3, bean.getLogin());
  pstmt.setString(4, bean.getPassword());
  pstmt.setDate(5, new java.sql.Date(bean.getDob().getTime()));
  pstmt.setString(6, bean.getMobileNo());
  pstmt.setLong(7,bean.getLibraryCode());
  pstmt.setString(8,bean.getEmailId());
  pstmt.setString(9, bean.getGender());
  pstmt.setLong(10, bean.getRoleId());
  pstmt.setString(11, bean.getCreatedBy());
  pstmt.setString(12, bean.getModifiedBy());
  pstmt.setTimestamp(13, bean.getCreatedDatetime());
  pstmt.setTimestamp(14, bean.getModifiedDatetime());
  pstmt.setLong(15,bean.getId());
  pstmt.executeUpdate();
  conn.commit(); // End transaction
  pstmt.close();
 } catch (Exception e) {
  e.printStackTrace();
  log.error("Database Exception..", e);
  e.printStackTrace();
  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 void delete(UserBean bean) throws ApplicationException {
  
  Connection conn = null;
  try {
   conn = JDBCDataSource.getConnection();
   conn.setAutoCommit(false); // Begin transaction
   PreparedStatement pstmt = conn.prepareStatement("DELETE FROM LI_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 List search(UserBean bean, int pageNo, int pageSize) throws ApplicationException {
  log.debug("Model search Started");
  StringBuffer sql = new StringBuffer("SELECT * FROM LI_USER WHERE 1=1");

  if (bean != null) {
   if (bean.getId() > 0) {
    sql.append(" AND id = " + bean.getId());
   }
   if (bean.getLibraryCode() > 0) {
    sql.append(" AND librarycode = " + bean.getLibraryCode());
   }
   if (bean.getFirstName() != null && bean.getFirstName().length() > 0) {
    sql.append(" AND FirstNAME like '" + bean.getFirstName() + "%'");
   }
   
   if (bean.getLogin() != null && bean.getLogin().length() > 0) {
    sql.append(" AND LOGIN like '" + bean.getLogin() + "%'");
   }
   if (bean.getEmailId() != null && bean.getEmailId().length() > 0) {
    sql.append(" AND EmailId like '" + bean.getEmailId() + "%'");
   }
   
   

  }

  // 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);
   // sql.append(" limit " + pageNo + "," + pageSize);
  }

  System.out.println("user model search  :"+sql);
  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.setDob(rs.getDate(6));
    bean.setMobileNo(rs.getString(7));
    bean.setLibraryCode(rs.getLong(8));
    bean.setEmailId(rs.getString(9));
    bean.setGender(rs.getString(10));
    bean.setRoleId(rs.getLong(11));
    bean.setCreatedBy(rs.getString(12));
    bean.setModifiedBy(rs.getString(13));
    bean.setCreatedDatetime(rs.getTimestamp(14));
    bean.setModifiedDatetime(rs.getTimestamp(15));

    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 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.getFirstName());

  String message = EmailBuilder.getChangePasswordMessage(map);

  EmailMessage msg = new EmailMessage();

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

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

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

 }
 
 
 
}

Library managemenet System project in java

Note: If you need the source code you can contact me. We will provide complete source code with project reports and the team will configure the complete project at your machine remotely. We will explain the complete flow of the application with the source code.

Step by Step Tutorial to configure Java project

Viva Questions and answers for java project

Check new projects in java

 

4 thoughts on “Library management system project in java with source code”

  1. Pingback: library management system project in java with source code ⋆ Android Developers Blog

Leave a Comment

Your email address will not be published.