String subValue = req.getParameter(SUBMIT_PARAMETER); ... if(subValue.equals(READ_PARAMETER)) { performRead(req, res); } else if(subValue.equals(ADD_PARAMETER)) { performAdd(req, res); } else if(subValue.equals(DELETE_PARAMETER)) { performDelete(req, res); }
This code interprets the value of the submit parameter from the request object, and invokes the appropriate method in the application for each known request. An example of one of the methods is performRead, and is explained next.
BookInterface bookInterface = getBookInterface(req.getSession()); String bookId = getStockNo(req, res); try { BookBean book = bookInterface.readBook(bookId); outputBook(req, res, book); } catch(JavaBookException e) { outputBookException(req, res, e); } catch (Exception e) { outputException(req, res, e); }
This code defines a BookInterface class by passing the session object from the request object to the constructor of BookInterface.java. Then it gets the stock number from the request parameters, and makes a call to readBook on the interface. Finally, it registers the BookBean object with the JSP by calling outputBook.
private void outputBook(HttpServletRequest req, HttpServletResponse res, BookBean book) if(book != null) { req.setAttribute("book", book); } else { req.setAttribute("book", BookBean.msgBook("ERROR! book is null in output book")); }
This method binds the book as a request attribute to our JSP view, namely BookJsp.jsp. The JSP unpacks this book object and outputs its values.
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(VIEW_URL); try { dispatcher.forward(req, res); } catch(Exception e) { throw new RuntimeException(e); }
This method gets a dispatch object for the JSP view, and then forwards the request to it. With all the necessary attributes set up, the JSP view can output the book record correctly.