Spring MVC and Hibernate Web Application One-to-One Mapping Database Example [XML Configuration]

In this article, you will learn how to Create Spring MVC and Hibernate Web application with One-to-One mapping. And also you will learn how to integrate Spring MVC and Hibernate with XML Configuration. We will be creating a simple Book Management Application. So let’s get started.




Application Features:
    Book Management Application provides the following features,

  • Create book
    • single book – User can create/add single book to the application
    • multiple book – User can create/add multiple books to the application
  • Delete book – User can delete the book from application
  • Search book by
    • book type – User can search book by book type (Category)
    • book id – User can search book by book id
    • book name – User can search book by book name
  • Book quantity
    • Increase – User can increase the book quantity
    • Decrease – User can decrease the book quantity

Tools and Technologies Used:
    Following are the tools and technologies used to create application,

  • Spring 3.2.3
  • Hibernate 4.1.8
  • Java 7
  • Mysql connector 5.0.5
  • Eclipse Oxygen
  • Mysql workbench
  • Maven 3.1




Step 1: Create a database with name bookmanagement (you can give any name you want)

CREATE DATABASE bookmanagement;

Step 2: Create book_type and book_details tables on the database

book_type table

CREATE TABLE `book_type` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bookrtype` varchar(45) NOT NULL,
  `description` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

book_details table

CREATE TABLE `book_details` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bookid` varchar(45) NOT NULL,
  `bookname` varchar(45) NOT NULL,
  `price` varchar(45) NOT NULL,
  `comments` varchar(45) NOT NULL,
  `noofcopies` int(11) NOT NULL,
  `book_type` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

Step 3: Create a maven project with name bookmanagement

 

Step 4: Create 4 packages as shown in the image under src/main/java and add the following dependencies to the pom.xml file




<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>in.bushansirgur</groupId>
	<artifactId>bookmanagement</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>bookmanagement Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
	</properties>

	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>
		
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-orm</artifactId>
		    <version>3.2.3.RELEASE</version>
		</dependency>
		

		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.2.2</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.1.8.Final</version>
		</dependency>

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

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.0.5</version>
		</dependency>

		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.2.3.RELEASE</version>
		</dependency>


	</dependencies>
	<build>
		<finalName>bookmanagement</finalName>
	</build>
</project>

Step 5: Create jdbc.properties for database configuration in the src/main/java folder in the created project

jdbc.driverName=com.mysql.jdbc.Driver
jdbc.databaseurl=jdbc:mysql://localhost/bookmanagement
jdbc.username=root
jdbc.password=
jdbc.dialect=org.hibernate.dialect.MySQLDialect

Step 6: Create all the necessary java classes under the respective packages as shown in the Step 3 image

Step 7: Create web.xml and spring-servlet.xml configuration file under webapp/WEB-INF folder




Step 8: Create a sub-folder with a name jsp under the webapp/WEB-INF folder. Create a view file book.jsp and bookdetails.jsp under this sub-folder.

Step 9: Create resources folder under webapp and create 2 sub folders css and javascript under resources folder

Step 10: Download jquery core library, jquery UI library and add it to the respective folder as shown in the Step 3 image

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
</web-app>

spring-servlet.xml




<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	
	<context:component-scan base-package="in.bushansirgur" />
	<context:property-placeholder location="classpath:jdbc.properties" />
	  
	
	<mvc:resources mapping="/resources/**" location="/resources/" />
	<mvc:annotation-driven />

	<beans:bean id="jspViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="viewClass"
		value="org.springframework.web.servlet.view.JstlView" />
		<beans:property name="prefix" value="/WEB-INF/jsp/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	
	<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<beans:property name="driverClassName"  value="${jdbc.driverName}"/>
		<beans:property name="url" value="${jdbc.databaseurl}" />
		<beans:property name="username" value="${jdbc.username}" />
		<beans:property name="password" value="${jdbc.password}" />
	</beans:bean>
	
	
	 <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
     <beans:property name="dataSource" ref="dataSource" />
     <beans:property name="packagesToScan" value="in.bushansirgur.bookmanagement.form"/>	
       
       
        <beans:property name="hibernateProperties">
			<beans:props>
				<beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
				<beans:prop key="hibernate.format_sql">true</beans:prop>
				<beans:prop key="hibernate.generate_statistics">true</beans:prop>
				<beans:prop key="hibernate.jdbc.batch_size">30</beans:prop>
			</beans:props>
		</beans:property>
   </beans:bean>
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<beans:bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<beans:property name="sessionFactory" ref="sessionFactory" />
	</beans:bean> 

</beans:beans>

Book.java

package in.bushansirgur.bookmanagement.form;

import java.io.Serializable;

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


@Entity
@Table(name="book_type")
public class Book implements Serializable
{
	@Id
	@Column(name="id")
	@GeneratedValue
	private Integer id;
	
	@Column(name="bookrtype")
	private String bookType;
	
	@Column(name="description")
	private String description;
	
	public Book()
	{
		System.out.println("Inside Book Type cons()");
	}
	
	public Book(Integer id, String bookType)
	{
		this.id=id;
		this.bookType=bookType;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getBookType() {
		return bookType;
	}
	public void setBookType(String bookType) {
		this.bookType = bookType;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	
	@Override
	public String toString()
	{
		return "Book [id="+id+ " BookType="+bookType+"Description="+description+"]";
	}
	
}

BookDetails.java

package in.bushansirgur.bookmanagement.form;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@SuppressWarnings("serial")
@Entity
@Table(name = "book_details")
public class BookDetails implements Serializable {
	@Id
	@Column(name = "id")
	@GeneratedValue(generator = "system-increment")
	@GenericGenerator(name = "system-increment", strategy = "increment")

	private Integer id;
	@Column(name = "bookid")
	private String bookId;
	@Column(name = "bookname")
	private String bookName;
	@Column(name = "price")
	private String price;
	@Column(name = "comments")
	private String comment;
	@Column(name = "noofcopies")
	private Integer noOfCopies;

	@OneToOne
	@JoinColumn(name = "book_type")
	private Book bookType;

	public BookDetails() {
		System.out.println("Inside BookDetails Cons()");
	}

	public Integer getId() {
		return id;
	}

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

	public String getBookId() {
		return bookId;
	}

	public void setBookId(String bookId) {
		this.bookId = bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public String getPrice() {
		return price;
	}

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

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public Book getBookType() {
		return bookType;
	}

	public void setBookType(Book bookType) {
		this.bookType = bookType;
	}

	public Integer getNoOfCopies() {

		return noOfCopies;
	}

	public void setNoOfCopies(Integer noOfCopies) {
		this.noOfCopies = noOfCopies;
	}

	@Override
	public String toString() {
		return "BookDetails[id= " + id + "bookId=" + bookId + "bookName=" + bookName + "price=" + price + "comment="
				+ comment + "noOFCopies=" + noOfCopies + "BookType=" + bookType + "]";
	}

}

AddBook.java

package in.bushansirgur.bookmanagement.form;

import java.util.ArrayList;
import java.util.List;

public class AddBook 
{

	private List<BookDetails> bookdetails = new ArrayList<BookDetails>();

	public List<BookDetails> getBookdetails() {
		return bookdetails;
	}

	public void setBookdetails(List<BookDetails> bookdetails) {
		this.bookdetails = bookdetails;
	}

}

BookDao.java

package in.bushansirgur.bookmanagement.dao;

import java.util.List;

import in.bushansirgur.bookmanagement.form.AddBook;
import in.bushansirgur.bookmanagement.form.Book;
import in.bushansirgur.bookmanagement.form.BookDetails;

public interface BookDao 
{
	public List<BookDetails> listBooks();
	
	public List<Book> BookTypes();
	
	public Integer addOneBook(Integer bookId);

	public Integer saveOneBook(Integer bookId);
	
	public List<BookDetails>  serach(BookDetails bookDetails);
	
	public void removeBook(Integer id);
	
	public void saveDetails(AddBook details);
}

BookDaoImpl.java




package in.bushansirgur.bookmanagement.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import in.bushansirgur.bookmanagement.form.AddBook;
import in.bushansirgur.bookmanagement.form.Book;
import in.bushansirgur.bookmanagement.form.BookDetails;

@Repository
public class BookDaoImpl implements BookDao
{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public void saveDetails(AddBook details) 
	{
		for(BookDetails books:details.getBookdetails())
		{
			if(!(books.getBookId().equals(null)))
			{
			sessionFactory.getCurrentSession().save(books);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<BookDetails> listBooks()
	{
		
		List<BookDetails> list = sessionFactory.getCurrentSession().createQuery("from BookDetails").list();
		for(BookDetails book:list)
		System.out.println(book.toString());
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<Book> BookTypes() 
	{
		
		List<Book> list = sessionFactory.getCurrentSession().createQuery("from Book").list();
		for(Book book:list)
		System.out.println(book.toString());
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public Integer addOneBook(Integer bookId)
	{
		
		BookDetails book= new BookDetails();
		book = (BookDetails)sessionFactory.getCurrentSession().get(BookDetails.class, bookId);
		Integer copies=book.getNoOfCopies();
		book.setNoOfCopies(copies-1);
		sessionFactory.getCurrentSession().update(book);
		return book.getNoOfCopies();
	}
	
	@SuppressWarnings("unchecked")
	public Integer saveOneBook(Integer bookId)
	{
		
		BookDetails book= new BookDetails();
		book.setId(bookId);
		book = (BookDetails)sessionFactory.getCurrentSession().get(BookDetails.class, bookId);
		Integer copies=book.getNoOfCopies();
		book.setNoOfCopies(copies+1);
		sessionFactory.getCurrentSession().update(book);
		return copies+1;	
	}
	
	@SuppressWarnings("unchecked")
	public List<BookDetails>  serach(BookDetails bookDetails) 
		{
	
		 Integer Booktypes=bookDetails.getBookType().getId();
		 String BookId=bookDetails.getBookId();
		 String name=bookDetails.getBookName();
		 
		 Criteria criteria= sessionFactory.getCurrentSession().createCriteria(BookDetails.class);
		 Criterion criteria1=Restrictions.eq("bookType.id", bookDetails.getBookType().getId());
		 Criterion criteria2=Restrictions.eq("bookId", BookId);
		 Criterion criteria3=Restrictions.eq("bookName", name);
		 LogicalExpression logicEx1=null;
		 LogicalExpression logicEx2=null;
		 
		 
		 if(Booktypes !=null && BookId !="" && name !="")
		 	{ 
			
			 logicEx1=Restrictions.and(criteria1, criteria2);
			 List<BookDetails> l=criteria.add(Restrictions.and(logicEx1, criteria3)).list();	
			 System.out.println(l.toString());
			 return l;
		 	}
		 
		 if(Booktypes !=null && BookId !="" && name =="")
		  	{
			 return criteria.add(Restrictions.and(criteria1, criteria2)).list();
		  	}
		 
		 if(Booktypes !=null && name != "" && BookId =="")
		 	{
			 return criteria.add(Restrictions.and(criteria1, criteria3)).list();
		 	}
		 
		 if(BookId !="" && name !="" && Booktypes ==null)
		 	{
			 return criteria.add(Restrictions.and(criteria2, criteria3)).list();
		 	}
		 
		 if(Booktypes !=null && BookId =="" && name =="" )
		 	{
			 return criteria.add(Restrictions.eq("bookType.id", Booktypes)).list();
		 	}
		 
		 if(BookId !=null && name =="" && Booktypes ==null )
		 	{ 
			 return criteria.add(Restrictions.eq("bookId", BookId)).list();
		 	}
		 
		 if(name != null && Booktypes ==null && BookId =="" )
		  	{ 
			 return criteria.add(Restrictions.eq("bookName", name)).list();
		  	}
		
		return null;
	}

	
	
	@SuppressWarnings("unchecked")
	public void removeBook(Integer id) {
		
		BookDetails book = (BookDetails)sessionFactory.getCurrentSession().load(BookDetails.class, id);
		
		if(null != book) {
			sessionFactory.getCurrentSession().delete(book);
			sessionFactory.getCurrentSession().flush();
		}
	}

	


	
}

BookService.java

package in.bushansirgur.bookmanagement.service;

import java.util.List;

import in.bushansirgur.bookmanagement.form.AddBook;
import in.bushansirgur.bookmanagement.form.Book;
import in.bushansirgur.bookmanagement.form.BookDetails;


public interface BookService 
{
	public List<BookDetails> listBooks();

	public List<Book> BookTypes();
	
	public Integer addOneBook(Integer bookId);
	
	public Integer saveOneBook(Integer bookId);
	
	public List<BookDetails>  serach(BookDetails bookDetails);
	
	public void removeBook(Integer id);

	public void saveDetails(AddBook details) ;
}

BookServiceImpl.java

package in.bushansirgur.bookmanagement.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import in.bushansirgur.bookmanagement.dao.BookDao;
import in.bushansirgur.bookmanagement.form.AddBook;
import in.bushansirgur.bookmanagement.form.Book;
import in.bushansirgur.bookmanagement.form.BookDetails;

@Service
public class BookServiceImpl implements BookService {

	@Autowired
	private BookDao bookDao;

	@Transactional
	public void saveDetails(AddBook details) {
		bookDao.saveDetails(details);
	}

	@Transactional
	public List<BookDetails> listBooks() {
		System.out.println("inside list books in BookServiceImpl");
		return bookDao.listBooks();
	}

	@Transactional
	public List<Book> BookTypes() {
		return bookDao.BookTypes();
	}

	@Transactional
	public Integer addOneBook(Integer bookId) {
		return bookDao.addOneBook(bookId);
	}

	@Transactional
	public Integer saveOneBook(Integer bookId) {
		return bookDao.saveOneBook(bookId);
	}

	@Transactional
	public List<BookDetails> serach(BookDetails bookDetails) {
		return bookDao.serach(bookDetails);
	}

	@Transactional
	public void removeBook(Integer id) {
		bookDao.removeBook(id);
	}

}

BookController.java




package in.bushansirgur.bookmanagement.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

import in.bushansirgur.bookmanagement.form.AddBook;
import in.bushansirgur.bookmanagement.form.Book;
import in.bushansirgur.bookmanagement.form.BookDetails;
import in.bushansirgur.bookmanagement.service.BookService;


@Controller
public class BookController 
{
	@Autowired
	private BookService bookService;
	
	@RequestMapping("/home")
	public ModelAndView listBooks(@ModelAttribute("bookDetails") BookDetails bookDetails) 
		{
		
		ModelAndView modelAndView = new ModelAndView("book");
		List<Book> list = bookService.BookTypes();                    // All list of Book
		modelAndView.addObject("bookDetails",bookDetails);
		modelAndView.addObject("bookTypesList",list);
		modelAndView.addObject("bookList", bookService.listBooks());  // All list of BookDetails
		return modelAndView;
	
		}


	@RequestMapping("/bookdetails")
	public ModelAndView addBook(AddBook bookdetails,ModelAndView modelAndView) 
	{ 
		
		List<Book> books=bookService.BookTypes();  
		modelAndView.addObject("books", books);
		modelAndView.addObject("bookdetails", new AddBook());

		return modelAndView;
	}
	
	
	
	@RequestMapping("/save")
	public String saveDetails(@ModelAttribute("bookdetails") AddBook bookdetails)
	{

		
		bookService.saveDetails(bookdetails);
		return "redirect:/home";
	}

	@RequestMapping("/decreaseNoOfCopies")
	public void buyBook(HttpServletRequest request,HttpServletResponse response) throws IOException
		{
		Integer id=Integer.parseInt(request.getParameter("autoId"));
		Integer Nofcopies=bookService.addOneBook(id);
	
		response.getWriter().write(new Gson().toJson(Nofcopies));    // it will return the object
		}


	@RequestMapping("/increaseNoOfCopies")
	public void saveOneBook(HttpServletRequest request, HttpServletResponse response) throws IOException
			{
			Integer id=Integer.parseInt(request.getParameter("autoId"));
			Integer Nofcopies=bookService.saveOneBook(id);
		
			response.getWriter().write(new Gson().toJson(Nofcopies));    // it will return the object 
			}
		
		
	@RequestMapping("/search")
	public String searchTerms(@ModelAttribute("bookDetails") BookDetails bookDetails, Map<String, Object> map)
		{

		 map.put("bookTypesList",bookService.BookTypes());
		 List<BookDetails> listOfBook = bookService.serach(bookDetails);
		 map.put("bookList", listOfBook);	
	     return "book";
		}
	
	@RequestMapping("/delete/{bookId}")
	public String deleteBook(@PathVariable("bookId") Integer bookId)
	{
		
		bookService.removeBook(bookId);
		return "redirect:/home";
	}
		

}

book.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Books</title>
<link href="<c:url value="resources/css/jquery-ui.css"></c:url>" rel="stylesheet" type="text/css" />
<link href="<c:url value="resources/css/chegus-infotech-style-Hie.css"></c:url>" rel="stylesheet" type="text/css" />
</head>
<body>
<c:url value="/search" var="action"></c:url>
<form:form action="${action}" commandName="bookDetails" modelAttribute="bookDetails">
<table border="0" cellpadding="0" cellspacing="0" class="mainTable">
  <tr>
    <td class="headerText" >B<span>OOKS</span></td>
  </tr>
  <tr>
    <td class="subHeaderText"><h3>Book Search</h3></td>
  </tr>
  <tr>
    <td><table border="0" cellpadding="0" cellspacing="0" class="innerTable" >
        <tr>

          <td class="labelTextSearch">Book Type </td>
          <td class="fieldTextSearch">
          <form:select path="bookType.id">   
          	<option value="">---Select---</option>
          	<c:forEach  items="${bookTypesList}" var="bookTypes">
          	<form:option value="${bookTypes.id}">${bookTypes.bookType}</form:option>
          	</c:forEach>
          </form:select>
          </td> 
          
         
         <td class="labelTextSearch"> Book ID</td>
         <td class="fieldTextSearch"><form:input path="bookId" type="text" class="textStyle_130"/></td>
         <td class="labelTextSearch"> Book Name</td>
         <td class="fieldTextSearch"><form:input path="bookName" type="text" class="textStyle_130"/></td>
              
        </tr></table></td></tr>
        <tr><td class="rowSpace"></td></tr>
         <tr>
            <td><br />
            <div id="divbtns">
                <input name="Search" type="submit" id="Search" title="Search"  value="Search"/>
                <input type="button" value="Reset" name="resetbutton" onClick="refreshPage()"/></div></td>
          </tr>
     
   <tr >
    <td class="headerText">B<span>OOK INFO</span></td>
  </tr>
    <tr>
    <td><table border="0" cellpadding="0" cellspacing="0" class="innerTable tab" >
        <tr>
          <td width="10%"  class="subHeaderText" align = "center">Book Type </td>
          <td width="10%" class="subHeaderText" align = "center"> Book ID </td>
          <td width="12%"  class="subHeaderText" align = "center"> Book Name </td>
		   <td width="10%"  class="subHeaderText" align = "center">Price</td>
          <td width="10%" class="subHeaderText" align = "center">Comments</td>
		  <td width="10%" class="subHeaderText" align = "center">No of copies</td>
		   <td width="10%" class="subHeaderText" align = "center">you want to Buy ?</td>
		   <td width="12%" class="subHeaderText" align = "center">Add one more copy of Book</td>
		   <td width="10%" class="subHeaderText" align = "center">Delete</td>
		   
        </tr>
        
         <c:forEach items="${bookList}"  var="book" varStatus="loopCounter">
         <tr class="trClass${loopCounter.count}">
            
            <td align = "center"> ${book.bookType.bookType}</td>
            <td align = "center">${book.bookId}</td>

            <td align = "center">${book.bookName}</td>
            <td align = "center">${book.price}</td>
            <td align = "center">${book.comment}</td>
            <td align = "center" ><span id="nofCopy">${book.noOfCopies}</span></td>
            <td align = "center"><input type="button" value="buy" title="buy" id="${book.id}" onclick="$(this).getNoOfCopies('id')" class ="buy"/></td>
            <td align = "center"><input type="button" value="Add copy" title="Add copy" id="${book.id}" onclick="$(this).getAddNoOfCopies('id')"/></td>
            <td align = "center"><input type="button" value="Delete" title="Delete" onclick="javascript:deleteBook(${book.id})" /></td>
            
        </tr>
    	</c:forEach>
       
      </table></td>
  </tr>
  <tr><td class="rowSpace"></td></tr>
 <tr>
 <td><a href="bookdetails"><input type="button" value="create" title="create"/></a></td>
 </tr>
</table>

</form:form>
<script language="javascript" src="resources/javascript/jquery-1.8.3.js"></script>
<script language="javascript" src="resources/javascript/jquery-ui.js"></script>
<script language="javascript" src="resources/javascript/book.js"></script>
</body>
</html>

bookdetails.jsp



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="s"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Books</title>
<link
	href="<c:url value="resources/css/chegus-infotech-style-Hie.css"></c:url>"
	rel="stylesheet" />
<link href="<c:url value="resources/css/jquery-ui.css"></c:url>"
	rel="stylesheet" />
</head>
<body class="bodyClass">
	<c:url var="action" value="/save.html"></c:url>
	<s:form action="${action}" method="post" commandName="bookdetails"
		modelAttribute="bookdetails">
		<table border="0" cellpadding="0" cellspacing="0" class="mainTable">
			<tr>
				<td class="headerText"><span>BOOKS</span></td>
			</tr>
			<tr>
				<td class="subHeaderText"><h3>Book Details</h3></td>
			</tr>
			<tr>
				<td>
					<table border="0" cellpadding="0" cellspacing="0"
						class="innerTable">
						<tbody id="coun">
						</tbody>
						<tr>
							<td><fieldset>
									<legend>Book Details</legend>

									<table id="mytable" cellpadding="0" cellspacing="0"
										width="100%" class="noborder">
										<tbody id="cur">
											<tr>
												<td class="labelTextDetails">Book type</td>
												<td class="labelTextDetails">Book ID</td>
												<td class="labelTextDetails">Book Name</td>
												<td class="labelTextDetails">Price</td>
												<td class="labelTextDetails">Comments</td>
												<td class="labelTextDetails">No of Copies</td>
												<td><input type="button" value="AddRow" id="add"
													class="add" /></td>
											</tr>

											<tr id="Dup0">

												<td class="fieldText"><s:select
														path="bookdetails[0].bookType.id" name="select"
														class="dropdown_Free">
														<c:forEach items="${books}" var="book">
															<s:option value="${book.id}">${book.bookType}</s:option>
														</c:forEach>
													</s:select></td>
												<td class="fieldText"><s:input
														path="bookdetails[0].bookId" id="bookid" /></td>
												<td class="fieldText"><s:input
														path="bookdetails[0].bookName" id="bookname" /></td>
												<td class="fieldText"><s:input
														path="bookdetails[0].price" id="price" /></td>
												<td class="fieldText"><s:input
														path="bookdetails[0].comment" id="price" /></td>
												<td class="fieldText"><s:input
														path="bookdetails[0].noOfCopies" id="noofcopies" /></td>

											</tr>

										</tbody>
									</table>
								</fieldset></td>
						</tr>
					</table>
				</td>
			</tr>

			<tr>
				<td class="rowSpace"></td>
			</tr>

			<tr>
				<td class="Space"></td>
			</tr>
		</table>
		<input type="submit" value="Submit" />
		<a href="home"><input type="button" value="Cancel" /></a>
	</s:form>
<script language="javascript" src="resources/javascript/jquery-1.8.3.js"></script>
<script language="javascript" src="resources/javascript/jquery-ui.js"></script>
<script language="javascript" src="resources/javascript/bookdetails.js"></script>
</body>
</html>

book.js

$(document).ready(function(){
	
	
	$.fn.getNoOfCopies=function(id)
	{
		
	var trId=$(this).closest('tr').attr("class");     
	
	var copy1=$("."+trId).find("#nofCopy").html();     
	
	var Id=$(this).attr(id);                          
	
	if(copy1<=0)
	{
		$("."+trId).find('.buy').attr('disabled', true);	
		alert("There are no books to buy!");
		return true;
	}
	else{
		$.ajax({
	    type: "POST",
	    url: "./decreaseNoOfCopies",
	    data: 
	    {
	    	"autoId":Id
	    } ,
	    dataType: "json",
	    success: function(response) 
	    {
	    	$("."+trId).find('#nofCopy').html(response);     
	    }
	});
	}
	};
	
	$.fn.getAddNoOfCopies=function(id)
	{
		var trId=$(this).closest('tr').attr("class");
		var Id=$(this).attr(id);
		
		
			$.ajax(
					{
		    type: "POST",
		    url: "./increaseNoOfCopies",
		    data: 
		    {
		    	"autoId":Id
		    } ,
		    dataType: "json",
		    success: function(response) 
		    {
		    	$("."+trId).find('#nofCopy').html(response);
		    		     
		    }
			});

		};
		
});
function refreshPage() 
{
       window.location.reload("true");

} 

function deleteBook(bookId){
    if(confirm('Do you want to delete this Book ?')){
        var url = 'delete/'+bookId;
       window.location.href = url;
    }
}

bookdetails.js

$("document").ready(function() {
	$("input.add").click(function() { 
		var last = $("#mytable").find("tr:last"); 
		var new1 = last.clone();  
		new1.attr("id", function()
		{
			var newid = $(this).attr("id"); 
			var regIdMatch = /^(.+)(\d+)$/;  
			var autoid = newid.match(regIdMatch); 
			var res = parseInt(autoid[2]) + 1; 
			return autoid[1] + res; 

		});
		new1.find("select").each(function() {

			$(this).attr("name", function() {
				var newid = $(this).attr("name"); 
				var regIdMatch = /^(.+)(\d+)(.+)$/; 
				var autoid = newid.match(regIdMatch); 
				var res = parseInt(autoid[2]) + 1; 
				var v = autoid[1] + res + autoid[3]; 
				return v;
			});

		}).val('');

		new1.find("input").each(function() {
			$(this).attr("name", function() {
				var newid = $(this).attr("name");
				var regIdMatch = /^(.+)(\d+)(.+)$/;
				var autoid = newid.match(regIdMatch);
				var res = parseInt(autoid[2]) + 1;
				return autoid[1] + res + autoid[3];

			}).val('');
		});
		last.after(new1);

	});
});

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="./home.html"></jsp:forward>
</body>
</html>




Once you are done with creating source and configuration files, run the application. 

That’s it for this article, i hope this article helped you in some way or the other way. Please share this post with your colleagues and friends.

Love this post?


Help me to buy a cup of coffee/Support us by donating.
All the donations will be going to the website maintenance/improvement.

Pay Now

Thanks and Regards,
Bhushan SC




About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

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