Master java skills

Spring Boot + MVC + JSP

Library Management System

In this tutorial, we are going to develop a small Library Management System.

Step 1 : Create a spring boot project and add following dependencies in your pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javatrainingschool</groupId>
	<artifactId>LibraryManagementApp</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>LibraryManagementApp</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Step 2 : application.properties file

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

server.port = 8081

spring.application.name= Library Management System

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true

spring.h2.console.enabled=true

Step 3 : Entity class Book.java

package com.sks.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book_tb")
public class Book {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	private String name;
	private String author;
	private int price;
	private String status; // true-available and false-borrowed
	private int borrowedForDays;

	public Book(int id, String name, String author, int price, String status, int borrowedForDays) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.price = price;
		this.status = status;
		this.borrowedForDays = borrowedForDays;
	}

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

	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", author=" + author + ", price=" + price + ", status=" + status
				+ ", borrowedForDays=" + borrowedForDays + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public int getBorrowedForDays() {
		return borrowedForDays;
	}

	public void setBorrowedForDays(int borrowedForDays) {
		this.borrowedForDays = borrowedForDays;
	}

}

Step 4 : Repository interface

package com.javatrainingschool.repo;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.javatrainingschool.entity.Book;

public interface BookRepository extends CrudRepository<Book, Integer> {
	
	
	public List<Book> findByName(String name);

}

Step 5 : Controller class

package com.sks.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sks.entity.Book;
import com.sks.repo.BookRepository;

@Controller
@RequestMapping("/library")
public class BookController {
	
	@Autowired
	private BookRepository bookRepo;
	
	@RequestMapping("/home")
	public String home(Model model) {
		model.addAttribute("appName", "Java Training School Library");
		return "home";
	}

	@RequestMapping("/display")
	public String displayBookInfo(Model model) {

		List<Book> allBooks = (List<Book>) bookRepo.findAll();
		model.addAttribute("books", allBooks);
		
		if(allBooks.isEmpty())
			model.addAttribute("msg", "Unfortunately, the library is empty now. Let's"
					+ "contribute by adding some books");
		else {
			if(model.getAttribute("msg") == null)
				model.addAttribute("msg", "Welcome to Java Traning School Library");
		}

		return "displayBook";
	}

	@GetMapping("/borrowForm/{id}")
	public String displayBorrowForm(@PathVariable String id, Model model) {

		Book book = bookRepo.findById(Integer.parseInt(id)).get();

		model.addAttribute("book", book);

		return "borrowBook";
	}

	@PostMapping("/borrow")
	public String borrow(@RequestParam int id, Model model) {

		Book book = bookRepo.findById(id).get();
		book.setStatus("Borrowed");

		bookRepo.save(book);

		model.addAttribute("msg", "Book borrowed successfuly. Please return within a month's time");

		return displayBookInfo(model);
	}

	@GetMapping("/addBookForm")
	public String displayAddBookForm(Model model) {
		
		model.addAttribute("book", new Book());

		return "addBook";
	}

	@PostMapping("/addBook")
	public String addBook(@ModelAttribute("book") Book book, Model model) {

		book.setStatus("available");
		bookRepo.save(book);
		
		model.addAttribute("msg", "Book added successfully. Thanks");

		return displayBookInfo(model);
	}

}

Step 6 : Create jsp files and keep them under webapp/WEB-INF/jsp folder as shown below

home.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>   
<head>
<title>Home Page</title>
</head>
<body>
	<h1>Hey, hope you are doing excellent today !</h1>
	<p>
		Welcome to spring boot app - <h3>${appName}</h3><br>
		Would you like to pay a visit?
		<a href="/library/display">Try Now</a>
		
	</p>
</body>
</html>

displayBook.jsp file

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<body>

	<h1>Welcome to Java Training School Library</h1><br>
	<div> ${msg}  </div><br>
	<table border="2" width="70%" cellpadding="2">
		<tr>
			<th>Id</th>
			<th>Book Name</th>
			<th>Author</th>
			<th>Price</th>
			<th>Status</th>
			<th>Borrow</th>
		</tr>
		<c:forEach var="book" items="${books}">
			<tr>
				<td>${book.id}</td>
				<td>${book.name}</td>
				<td>${book.author}</td>
				<td>${book.price}</td>
				<td>${book.status}</td>
				<c:if test="${book.status == 'available'}">  
   					<td><a href="borrowForm/${book.id}">Borrow</a></td>  
				</c:if> 
			</tr>
		</c:forEach>
	</table>
	<br />
	<a href="addBookForm">Add a Book</a>
</body>
</html>

addBook.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<body>
	<h1>Add Book</h1>
	<form:form method="post" action="addBook" modelAttribute="book">
		<table>
			<tr>
				<td>Book Name :</td>
				<td><form:input path="name" /></td>
			</tr>
			<tr>
				<td>Author :</td>
				<td><form:input path="author" /></td>
			</tr>
			<tr>
				<td>Price :</td>
				<td><form:input path="price" /></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="Save Book" /></td>
			</tr>
		</table>
	</form:form>
</body>
</html>

borrowBook.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<body>
	<h1>Borrow book</h1>
	<form:form method="post" action="/library/borrow">
		<table border="2" width="70%" cellpadding="2">
			<tr>
				<th>Id</th>
				<th>Book Name</th>
				<th>Author</th>
				<th>Price</th>
				<th>Status</th>
			</tr>
			<tr>
				<td>${book.id}</td>
				<td>${book.name}</td>
				<td>${book.author}</td>
				<td>${book.price}</td>
				<td>${book.status}</td>
			</tr>
		</table>
		<br /> <input type="submit" value="Borrow">
		<input type="hidden" name="id" value="${book.id}" />
	</form:form>
</body>
</html>

Step 7 : If you want to pre-populate some data, then add one data.sql file under src/main/resources folder

insert into book_tb (id, name, author, price, status, borrowed_For_Days) values(11, 'Learn Java', 'Mr Ashok', 400, 'available',0);
insert into book_tb (id, name, author, price, status, borrowed_For_Days) values(12, 'Tomb of sand', 'Gitanjali Shree', 300, 'available',0);
insert into book_tb (id, name, author, price, status, borrowed_For_Days) values(13, 'The white tiger', 'Arvind Adiga', 500, 'available',0);
insert into book_tb (id, name, author, price, status, borrowed_For_Days) values(14, 'Two states', 'Chetan Bhagat', 600, 'available',0);

Step 8 : Run and test the application

home url – http://localhost:8081/library/home

displaybook page

addBook page

After add book is successful

Borrow a book page

After borrowing is successful

That’s it for now. Thanks for reading this tutorial.