Advertisement
haithienht

Java Persistence (Books)

Oct 4th, 2019
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.61 KB | None | 0 0
  1. 1. Tạo web app BookCrud
  2. 2.0 Tạo bảng Books (BookID, Title, Price) trong DB Demo4 nếu chưa tạo
  3. 2.1 Mở admin console của Glassfish > Add Connection Pool
  4. + Name: Demo4
  5. + Type: javax.sql.DataSource
  6. + Vendor: MicrosoftSqlServer
  7. + Introspect: Enabled
  8. Next
  9. + user: sa
  10. + databaseName: Demo4
  11. + password:
  12. + serverName: localhost
  13. + URL: jdbc:sqlserver://localhost:1433;databaseName=Demo4
  14.  
  15. 2.2 Add Resource
  16. + name: jdbc/demo
  17. + chọn Pool vừa tạo
  18.  
  19. 3. Dừng Glassfish.
  20. Add > Other > Persistence > Entity Classes from Database > chọn dataSource mới tạo > chọn bảng Books > Next
  21. đặt trong package vn.aptech.entity rồi Finish
  22.  
  23. 4. Tạo Servlet ControllerServlet trong vn.aptech.servlet
  24. Insert Code > Use Entity Manager
  25. Thêm đoạn sau ở cuối:
  26.  
  27. public List<Books> getBooks(){
  28. List<Books> result = new ArrayList<>();
  29. try {
  30. utx.begin();
  31. Query q = em.createQuery("SELECT o FROM Books o");
  32. result = q.getResultList();
  33. utx.commit();
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. return result;
  38. }
  39.  
  40. public Books getBook(int id) {
  41. Books b = new Books();
  42. try {
  43. utx.begin();
  44. b = em.find(Books.class, id);
  45. utx.commit();
  46. } catch (Exception e) {
  47. Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
  48. throw new RuntimeException(e);
  49. }
  50. return b;
  51. }
  52.  
  53. public boolean create(Books b){
  54. try {
  55. utx.begin();
  56. em.persist(b);
  57. utx.commit();
  58. } catch (Exception e) {
  59. Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
  60. throw new RuntimeException(e);
  61. }
  62. return true;
  63. }
  64.  
  65. public boolean update(Books b){
  66. try {
  67. utx.begin();
  68. em.merge(b);
  69. utx.commit();
  70. } catch (Exception e) {
  71. Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
  72. throw new RuntimeException(e);
  73. }
  74. return true;
  75. }
  76.  
  77. public boolean delete(int id){
  78. try {
  79. utx.begin();
  80. em.remove(em.find(Books.class, id));
  81. utx.commit();
  82. } catch (Exception e) {
  83. Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
  84. throw new RuntimeException(e);
  85. }
  86. return true;
  87. }
  88.  
  89. 5. New Standard Deployment Descriptor (web.xml), qua tab Pages, gõ ControllerServlet vào phần Welcome files
  90.  
  91. 6. Thêm đoạn sau trong phần try ở method processRequest của ControllerServlet
  92. String action = request.getParameter("action");
  93. if (action == null) {
  94. request.setAttribute("books", getBooks());
  95. request.getRequestDispatcher("viewAll.jsp").forward(request, response);
  96. } else if (action.equals("add")) {
  97. response.sendRedirect("add.jsp");
  98. } else if (action.equals("addProcess")) {
  99. Books b = new Books();
  100.  
  101. b.setBookID(Integer.parseInt(request.getParameter("BookID")));
  102. b.setTitle(request.getParameter("Title"));
  103. b.setPrice(Integer.parseInt(request.getParameter("Price")));
  104.  
  105. create(b);
  106. response.sendRedirect("ControllerServlet");
  107. } else if (action.equals("delete")) {
  108. String id = request.getParameter("BookID");
  109. delete(Integer.parseInt(id));
  110. response.sendRedirect("ControllerServlet");
  111. } else if (action.equals("update")) {
  112. String id = request.getParameter("BookID");
  113. Books b = getBook(Integer.parseInt(id));
  114. request.setAttribute("book", b);
  115. request.getRequestDispatcher("update.jsp").forward(request, response);
  116. } else if (action.equals("updateProcess")) {
  117. Books b = new Books();
  118.  
  119. b.setBookID(Integer.parseInt(request.getParameter("BookID")));
  120. b.setTitle(request.getParameter("Title"));
  121. b.setPrice(Integer.parseInt(request.getParameter("Price")));
  122.  
  123. update(b);
  124. HttpSession session = request.getSession();
  125. session.setAttribute("success", "Done.");
  126. response.sendRedirect("ControllerServlet?action=update&BookID="+b.getBookID());
  127. }
  128.  
  129. 7. Tạo JSP: viewAll.jsp và đưa đoạn sau vào:
  130. <h1>Book Index</h1>
  131. <div><a href="ControllerServlet?action=add">Add new Book</a></div>
  132. <br/>
  133. <table border="1" style="margin-top: 5px">
  134. <thead>
  135. <tr>
  136. <th>ID</th>
  137. <th>Tittle</th>
  138. <th>Price</th>
  139. <th colspan="2">Action</th>
  140. </tr>
  141. </thead>
  142. <tbody>
  143. <%
  144. List<Books> list = (List<Books>)request.getAttribute("books");
  145. for (Books b : list) {
  146. %>
  147. <tr>
  148. <td><%= b.getBookID() %></td>
  149. <td><%= b.getTitle()%></td>
  150. <td><%= b.getPrice()%></td>
  151. <td><a href="ControllerServlet?action=update&BookID=<%=b.getBookID()%>">Update</a></td>
  152. <td><a href="ControllerServlet?action=delete&BookID=<%=b.getBookID()%>" onclick="return confirm('Are you sure to delete this?')">Delete</a></td>this?')">Delete</a></td>
  153. </tr>
  154. <%
  155. }
  156. %>
  157. </tbody>
  158. </table>
  159.  
  160. 8. Tạo trang add.jsp và thêm đoạn sau
  161. <h1>Book - Add new</h1>
  162. <div><a href="ControllerServlet">Back to Index</a></div>
  163. <form action="ControllerServlet?action=addProcess" method="POST">
  164. <table>
  165. <tbody>
  166. <tr>
  167. <td>ID:</td>
  168. <td><input type="text" name="BookID"></td>
  169. </tr>
  170. <tr>
  171. <td>Title:</td>
  172. <td><input type="text" name="Title"></td>
  173. </tr>
  174. <tr>
  175. <td>Price:</td>
  176. <td><input type="number" name="Price"></td>
  177. </tr>
  178. <tr>
  179. <td></td>
  180. <td><input type="submit" name="btnAdd" value="Add this Book"></td>
  181. </tr>
  182. </tbody>
  183. </table>
  184. </form>
  185.  
  186. 9. Tạo trang update.jsp và thêm đoạn sau
  187. <h1>Book - Update</h1>
  188. <p style="color:green">
  189. <%
  190. if (session.getAttribute("success") != null) {
  191. out.print(session.getAttribute("success"));
  192. session.removeAttribute("success");
  193. }
  194. %>
  195. </p>
  196. <div><a href="ControllerServlet">Back to Index</a></div>
  197. <form action="ControllerServlet?action=updateProcess" method="POST">
  198. <table >
  199. <tbody>
  200. <tr>
  201. <td>ID:</td>
  202. <td><input type="number" name="BookID" value="${book.bookID}" readonly="true" style="background-color: lightgray"></td>
  203. </tr>
  204. <tr>
  205. <td>Title:</td>
  206. <td><input type="text" name="Title" value="${book.title}"></td>
  207. </tr>
  208. <tr>
  209. <td>Price:</td>
  210. <td><input type="number" name="Price" value="${book.price}"></td>
  211. </tr>
  212. <tr>
  213. <td></td>
  214. <td><input type="submit" name="btnAdd" value="Update this Book"></td>
  215. </tr>
  216. </tbody>
  217. </table>
  218. </form>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement