Advertisement
haithienht

[Java EE] DemoStruts2

Oct 22nd, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. 1. Tạo new prj, tới cuối chọn framework Struts 2, tick thêm Create example page
  2.  
  3. 2. Add driver jdbc
  4.  
  5. 3. Tạo class Book, khai báo các thuộc tính và các construtor, refactor
  6.  
  7. 4. Tạo BookDal
  8. private Connection getConnection() throws ClassNotFoundException, SQLException{
  9. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  10. String sql = "jdbc:sqlserver://localhost:1433;databaseName=Demo";
  11. return DriverManager.getConnection(sql, "sa", "password123");
  12. }
  13.  
  14. public List<Book> getBooks(){
  15. List<Book> result = new ArrayList<>();
  16. try {
  17. Connection con = getConnection();
  18. String sql = "SELECT * FROM Books";
  19. PreparedStatement stm = con.prepareStatement(sql);
  20. ResultSet rs = stm.executeQuery();
  21. while(rs.next()){
  22. Book b = new Book();
  23. b.setBookID(rs.getInt(1));
  24. b.setTitle(rs.getString(2));
  25. b.setPrice(rs.getInt(3));
  26. result.add(b);
  27. }
  28. rs.close();
  29. stm.close();
  30. con.close();
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. return result;
  35. }
  36.  
  37. 5. New > Other > Struts2 > Action: DisplayAction trong package vn.aptech.action
  38.  
  39. public class DisplayAction extends ActionSupport{
  40.  
  41. BookDal dal = new BookDal();
  42.  
  43. public DisplayAction() {
  44. }
  45.  
  46. @Override
  47. public String execute() throws Exception {
  48. return ActionSupport.SUCCESS;
  49. }
  50.  
  51. public List<Book> GetBooks() {
  52. return dal.getBooks();
  53. }
  54. }
  55.  
  56. 6. Tạo trang display.jsp và thêm vào đầu:
  57. <%@taglib uri="/struts-tags" prefix="s" %>
  58. và thêm vào:
  59.  
  60. <h1>Display Books</h1>
  61. <table border="1">
  62. <thead>
  63. <tr>
  64. <th>Book ID</th>
  65. <th>Title</th>
  66. <th>Price</th>
  67. </tr>
  68. </thead>
  69. <tbody>
  70. <s:iterator value="books">
  71. <tr>
  72. <td><s:property value="bookID"/></td>
  73. <td><s:property value="title"/></td>
  74. <td><s:property value="price"/></td>
  75. </tr>
  76. </s:iterator>
  77. </tbody>
  78. </table>
  79. 7. Thêm trang index.jsp
  80.  
  81. 8. Vào web.xml đổi welcome-file thành index.jsp
  82.  
  83. 9. Copy example.xml rồi paste tại chỗ, đổi tên lại thành aptechaction.xml
  84. <package name="vn.aptech.action" namespace="/" extends="struts-default">
  85. <action name="DisplayAction" class="vn.aptech.action.Display">
  86. <result name="success">/display.jsp</result>
  87. </action>
  88. </package>
  89.  
  90. 10. Vào struts.xml thêm
  91. <include file="aptechaction.xml"/>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement