Java-Business-Application/C2/Issuing-and-Returning-a-book/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title of the script: Issuing and returning a book

Author:arya

Keywords:issuing, returning, book


Visual Cue Narration
Slide 1 Welcome to the spoken-tutorial on Issuing and returning a book.
Slide 2 In this tutorial, we will learn how to :
  • Fetch all the user details
  • Issuing a book
  • Returning a book


Slide 3

Software Requirements


Here we are using
  1. Ubuntu Version 12.04
  2. Netbeans IDE 7.3
  3. JDK 1.7
  4. Firefox web-browser 21.0

You can use any web-browser of your choice.

Slide 4

Prerequisites

To follow this tutorial you must have knowledge of


  1. Basics of Java Servlets and JSPs
  2. Creating and viewing inventories

If not, for relevant tutorials please visit our website.

In the earlier tutorial, we had seen how the Admin Section works.
Here, in this tutorial we have added more functionalities to the Admin Section.
Switch to the browser. Let us switch to the browser.
Login as the admin. Let us login again as the admin.
Point to the two options in the Admin Section Page. We can see that we have two more options in the Admin Section Page - List Users and Checkout/Return Book.
Come to the IDE. Now, let us come to the IDE.
Go to adminSection dot jsp. Go to adminSection dot jsp.
Highlight <input type="radio" name="menuselection" value="listusers">List Users<br>

<input type="radio" name="menuselection" value="checkoutbook">Checkout/Return Book<br>


We can see that there are two more radio buttons.

One for List Users and the other for Checkout/Return Book.

Switch back to the browser. Now, switch back to the browser.
Click on the radio button for List Users. We will click on the radio button for List Users.
Point to the list of all the users. It has all the details like First Name, Surname, Age, Gender and Username.



The steps are similar to the earlier two options.

We saw them in the previous tutorial.

Click on Checkout/Return Book. Now, let us click on the next option which is to Checkout or Return Book.
We get a form which allows you to checkout as well as return book.
We will now see the code for the same.
Switch back to the IDE. Switch back to the IDE.
Highlight (menuSelection.equals("checkoutbook")) We clicked on Checkout/Return Book.

So menuselection is equal to Checkout/Return Book.

Highlight RequestDispatcher requestDispatcher = req.getRequestDispatcher("checkOut.jsp");

requestDispatcher.forward(req, resp);


The steps are the same that we saw for List Books.


But here, we forward the request to checkOut.jsp using RequestDispatcher.

Go to checkout.jsp. Now, let us come to checkOut dot jsp.
Highlight <td><input type='radio' name='bkgroup1' value=<%=book.getBookId()%> /></td> This page is similar to that of listBooks dot jsp.

Except that we have a radio button against each book.

So that we can Checkout/Return a book.

Highlight User name:<input type='text' name='username' value="<%=checkout.getUserName()%>"> We have a username field to get the username of the user who has to checkout book.
Highlight Date of Return:<input type="text" name="dateofreturn" value=<%= sevenDaysAfterNowString %> />


We also have a Date field to set the return date of the book.
Highlight <%

SimpleDateFormat dateFormatter = new SimpleDateFormat();


Date today = new Date();

String todayString = dateFormatter.format(today);

System.out.println(todayString);

Calendarcalendar = new GregorianCalendar();

calendar.add(Calendar.DAY_OF_YEAR, 7);

Date sevenDaysAfterNow = calendar.getTime();

String sevenDaysAfterNowString = dateFormatter.format(sevenDaysAfterNow);%>


We set the return date as one week from current date.


This is done using the class Calendar.

The add function of the class takes two parameters.

First is the present day of the year.

Second is the number of days to be added to the present day.

We have added seven days.

Highlight <form action='CheckOutServlet' method='POST'> Now note that the form action is equal to CheckoutServlet.
Switch back to the browser. Now, let us come back to the browser.
Click on the radio button against Book ID 1. We will now click on BookId 1.
Type the username as arya. Type the username as arya.
Point to Return Date. We see that the return date is one week from today’s date.
Point to Available copies 9. Note that the number of Available Copies is 9.
Click on Checkout Book. Click on Checkout Book.
Point to Checkout Success Page. We get the Checkout Success Page.
Click on here to come back to Admin Section Page. We will click on here to come back to Admin Section Page.
Click on Checkout/Return Book. Again click on Checkout/Return Book.
We can see that the number of Available Copies reduces to 8.
We will see the code for this now.
Come back to the IDE. Come back to the IDE.
Go to CheckoutServlet.java. Go to CheckoutServlet.java.
Highlight List<String> errorMsgs = new ArrayList<String>(); Note that we have set the errorMsgs list.
Highlight request.setAttribute("errorMsgs", errorMsgs); We have set the errorMsgs in the request.
Highlight String userName = request.getParameter("username"); We get the username from the request using getParameter.
Highlight String checkout_book = request.getParameter("checkout");

String return_book = request.getParameter("return");

//String dateOfCheckout=request.getParameter("dateofcheckout");

String returndate=request.getParameter("dateofreturn");

String id = request.getParameter("bkgroup1");


Similarly we get the checkout_book, return_book, returndate and book id.
Highlight int book_id = Integer.parseInt(id); Next, we parse the BookId as Integer from the Id.
Highlight if (userName.length() == 0) {

errorMsgs.add("Please enter the user name");

}

if (id.length() == 0) {

errorMsgs.add("Please click on the book you want to checkout");

}


We validate the username and book id.
Highlight if (checkout_book == null && return_book == null) {

errorMsgs.add("Please select either checkout/return option!");

}


We also validate if Checkout_book and Return_Book is null.
Highlight if (checkout_book != null return_book != null) { Then, we validate if either of them is not null.
Highlight userExists = userExists(con, userName); Here, we check if the user exists in the system using userExists method.


We then store the returned value of the method in userExists variable.

Come to userExists method. Now, we will see what we do in this method.
Highlight stmt = con.prepareStatement("select username from Users where username=?");

stmt.setString(1, userName);

ResultSet rsUser = stmt.executeQuery();

First we execute the query to check if the username exists in the table.
Highlight int userExists = 0; Here we initialize the integer variable userExists to 0.
Highlight if (rsUser.next()) {

userExists = 1;

}

return userExists;

}

If the username exists we set userExists to 1.

We then return the value of userExists.

Highlight if (userExists == 0) {

errorMsgs.add("User does not exist in system");

}

So, if the method returns 0, it means the user does not exist in the system.
Highlight else {

bookIssued = bookAlreadyIssued(con, userName, book_id);

}


If user exists then we call the bookAlreadyIssued method.


We then store the returned value of the method in bookIssued.


Here, we check if the same book has already been issued by the same user.

Now, let us come to bookAlreadyIssued method.
Highlight int bookAlreadyIssued = 0; Here, we have set an integer variable bookAlreadyIssued to 0.
Highlight pst = con.prepareStatement("select book_id from Checkout where Username=? and book_id=?");

pst.setString(1, userName);

pst.setInt(2, book_id);

rsBooks = pst.executeQuery();


We execute the query to check if a book with the same bookid is issued by the same user.


We get bookid from Checkout table.



Highlight if (rsBooks.next()) {

bookAlreadyIssued = 1;

}

If BookId exists then, set the variable bookAlreadyIssued to 1.


We then return the value of bookAlreadyIssued.


If the method returns 1 then it means the same user has already borrowed this book.

Now, come back to the browser. Now, come back to the browser.

Let us now try to checkout the same book by the same user.

Again type the username as arya. Type the username as arya.
Click on BookId 1. Click on the radio button against BookId 1.
Then click on Checkout book.
Highlight Please correct the following errors!!!!

[The same user has already borrowed this book!]


We see that we get error message that the same user has already borrowed this book.
Switch back to the IDE. Now, switch back to the IDE.
Highlight if (userExists == 1 && checkout_book != null) {

checkout(con, book_id, bookIssued, request, userName, response, errorMsgs);

}


If userExists in the system and if checkout_book is not null, we call checkout method.
Come to checkout method. Let us see what we do in this method.
Highlight pst = con.prepareStatement("select bookname,availablecopies from Books where id=?");

pst.setInt(1, book_id);

rsBookById = pst.executeQuery();

Here, we get the availablecopies for corresponding id.


We get this from the Books table.

Highlight if (rsBookById.next()) {

availableCopies = rsBookById.getInt(2);

We then store the number of availablecopies into the variable availableCopies.
Highlight if (availableCopies > 0) {

if (bookIssued == 0) {


We check if availableCopies is greater than 0 and bookIssued is equal to 0.



Highlight String returndate = request.getParameter("dateofreturn"); We get the dateofreturn from the request and store in the returndate.



Highlight insertIntoCheckout(con, book_id, userName, returndate); We then, call the insertIntoCheckout method.
We will see what we do in this method.
Highlight private void insertIntoCheckout(Connection con, int book_id, String userName, String returndate) throws SQLException, ParseException {

PreparedStatement pst2 = null;

pst2 = con.prepareStatement("insert into Checkout values(null,?,?,?)");

pst2.setInt(1, book_id);

pst2.setString(2, userName);

pst2.setDate(3, new java.sql.Date(getDateFormat().parse(returndate).getTime()));

pst2.executeUpdate();

}


Here, we store the book_id, userName and returndate into the Checkout table.
Highlight decrementAvailableCopies(availableCopies, con, book_id); Then we call decrementAvailableCopies method.
We will see what we do in this method.
Highlight private void decrementAvailableCopies(int oldcopies, Connection con, int book_id) throws SQLException {

PreparedStatement pst4 = null;

oldcopies -= 1;

pst4 = con.prepareStatement("update Books set availablecopies=? where id=?");

pst4.setInt(1, oldcopies);

pst4.setInt(2, book_id);

pst4.executeUpdate();

}

Here, we execute query to decrement the availablecopies in the Books table by 1.
Highlight setCheckoutIntoRequest(book_id, userName, request); We call the setCheckoutIntoRequest method.

Let us come to this method.

Highlight private void setCheckoutIntoRequest(int book_id, String userName, HttpServletRequest request) {

CheckOut checkOut = new CheckOut();

checkOut.setBookId(book_id);

checkOut.setUserName(userName);

request.setAttribute("checkout", checkOut);

}


In this method, we set the checkout attribute into the request.
Highlight RequestDispatcher view = request

.getRequestDispatcher("successCheckout.jsp");

view.forward(request, response);

}


Then we we forward the request to successCheckout.jsp using RequestDispatcher.



Highlight else {

errorMsgs.add("There are no copies of the requested book available.");

}


If availableCopies is 0, then we print There are no copies of the requested book available.
Go to successCheckout.jsp. Now, let us come to successCheckout dot jsp.
Highlight CheckOut checkout = (CheckOut)request.getAttribute("checkout"); Here, first we get the checkout attribute from the request.
Highlight Your request to checkout Book ID<i> <%=checkout.getBookId() %></i> by <%=checkout.getUserName() %> was successful.

Click <a href='adminsection.jsp'>here</a> to try another checkout/return.<br/>


We then, display the success message for successful Checkout.
You can try out the different errors by yourself.
Switch to the browser. Now, let us return the book.So switch to the browser
Click on bookId 1 and type the username as arya. Click on bookId 1 and type the username as arya.
Click on Return book. Then, click on Return book.
Highlight Your request to return Book ID 1 by User ID arya was successful We get the success message that book has been successfully returned.
Click on here for another checkout/return. Click on here for another checkout/return.
So, we come back to the Admin Section Page.
Click on Checkout/Return Book. Click on Checkout/Return Book.
Highlight the number of available copies. We can see that the number of available copies for book id 1 has been incremented.
We will see the code for this.
Switch to the IDE. Now, let us come back to the IDE.
Open CheckoutServlet dot java. Open CheckoutServlet dot java.
Highlight else if (userExists == 1 && return_book != null) { We check if userExists is equal to 1 and return_book is not equal to null.
Highlight returnBook(con, book_id, bookIssued, userName, request, response, errorMsgs);


Then we call returnBook method.
Let us come to this method.
Highlight pst = con.prepareStatement("select totalcopies,availablecopies from Books where id=?");

pst.setInt(1, book_id);

rsBooks = pst.executeQuery();


Here, we select the totalcopies and availablecopies from Books for the book id.
Highlight if (rsBooks.next()) {

totcopies = rsBooks.getInt(1);

availcopies = rsBooks.getInt(2);


We store the totalcopies and availablecopies to totcopies and availcopies.
Highlight if ((availcopies + 1) <= totcopies) { Then we check if available copies exceed the totalcopies.
Let us come back to the browser.
Let us now return a book for a user who has not borrowed the book.
Type the username as mdhusein. Type the username as mdhusein.
Click on the book id 1. Click on the book id 1.
Click on Return Book. Then click on Return Book.
Highlight Please correct the following errors!!!!

[The given user has not borrowed this book!]


We can see that we get the error message here.The given user has not borrowed this book!!
Come back to the IDE. Now, come back to the IDE.
Highlight if (bookIssued == 1) { Here, we check if the bookIssued variable is equal to 1.
Highlight removeFromCheckout(con, userName, book_id); We then call the removeFromCheckout method.
Let us come to this method.
Highlight private void removeFromCheckout(Connection con, String username, int book_id) throws SQLException {

PreparedStatement pst2 = null;

pst2 = con.prepareStatement("delete from Checkout where username=? and book_id=?");

pst2.setString(1, username);

pst2.setInt(2, book_id);

pst2.executeUpdate();

}


Here, we execute the query to delete from Checkout table the entry which has checked out a book.
Highlight incrementAvailableCopies(availcopies, con, book_id); Here, we call the incrementAvailableCopies method.
Let us come to this method.
Highlight private void incrementAvailableCopies(int availcopies, Connection con, int book_id) throws SQLException {

PreparedStatement pst4 = null;

availcopies += 1;

pst4 = con.prepareStatement("update Books set availablecopies=? where id=?");

pst4.setInt(1, availcopies);

pst4.setInt(2, book_id);


pst4.executeUpdate();


}


Here, we increment the availablecopies by 1.


We execute the query to update in the Books table.

Highlight setReturnIntoRequest(book_id, userName, request); Then we call the setReturnIntoRequest method.
Let us come to this method.
Highlight private void setReturnIntoRequest(int book_id, String userName, HttpServletRequest request) {

CheckOut checkOut = new CheckOut();

checkOut.setBookId(book_id);

checkOut.setUserName(userName);

request.setAttribute("returnBook", checkOut);

}


Here, we set the returnBook attribute into the request.
Highlight RequestDispatcher view = request.getRequestDispatcher("successReturn.jsp");

view.forward(request, response);

}


Then we forward to the successReturn page using the RequestDispatcher.
The successReturn page is similar to that we had for successCheckout page.
come back to the login page. Now, come back to the browser. Come back to the login page.
Point to Visitor’s Home Page. We can see that we have a link called Visitor’s Home Page.
Click on Visitor’s Home Page. click on it.
Point list of all the books. We can see that we get a list of all the books available.
Slide 5

Summary

In this tutorial we have learnt:
  • To list all the users
  • To fetch a book
  • To return a book.


Slide 6

About slide


Watch the video available at the following link.
  1. It summarizes the Spoken Tutorial Project
  2. If you do not have good bandwidth you can download and watch it


Slide 7

About slide

The Spoken Tutorial Project Team
  1. Conducts workshops using spoken tutorials
  2. Gives certificates for those who pass an online test
  3. For more details please write to contact at spoken hyphen tutorial dot org


Slide 8

Acknowledgement

Spoken Tutorial Project is a part of the Talk to a Teacher Project
  1. It is supported by the National Mission on Education through ICT, MHRD, Government of India
  2. More information on this mission is available at
  3. http://spoken-tutorial.org/NMEICT-Intro


Slide 9

Contributor Slide

The Library Management System has been contributed by a leading software MNC, through their Corporate Social Responsibility Programme.


They have also validated the content for this spoken tutorial.


This is Arya Ratish from IIT Bombay signing off.


Thank you for joining.

Contributors and Content Editors

Arya Ratish