Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. Tạo new prj, tới cuối chọn framework Struts 2, tick thêm Create example page
- 2. Add driver jdbc
- 3. Tạo class Book, khai báo các thuộc tính và các construtor, refactor
- 4. Tạo BookDal
- private Connection getConnection() throws ClassNotFoundException, SQLException{
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- String sql = "jdbc:sqlserver://localhost:1433;databaseName=Demo";
- return DriverManager.getConnection(sql, "sa", "password123");
- }
- public List<Book> getBooks(){
- List<Book> result = new ArrayList<>();
- try {
- Connection con = getConnection();
- String sql = "SELECT * FROM Books";
- PreparedStatement stm = con.prepareStatement(sql);
- ResultSet rs = stm.executeQuery();
- while(rs.next()){
- Book b = new Book();
- b.setBookID(rs.getInt(1));
- b.setTitle(rs.getString(2));
- b.setPrice(rs.getInt(3));
- result.add(b);
- }
- rs.close();
- stm.close();
- con.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- 5. New > Other > Struts2 > Action: DisplayAction trong package vn.aptech.action
- public class DisplayAction extends ActionSupport{
- BookDal dal = new BookDal();
- public DisplayAction() {
- }
- @Override
- public String execute() throws Exception {
- return ActionSupport.SUCCESS;
- }
- public List<Book> GetBooks() {
- return dal.getBooks();
- }
- }
- 6. Tạo trang display.jsp và thêm vào đầu:
- <%@taglib uri="/struts-tags" prefix="s" %>
- và thêm vào:
- <h1>Display Books</h1>
- <table border="1">
- <thead>
- <tr>
- <th>Book ID</th>
- <th>Title</th>
- <th>Price</th>
- </tr>
- </thead>
- <tbody>
- <s:iterator value="books">
- <tr>
- <td><s:property value="bookID"/></td>
- <td><s:property value="title"/></td>
- <td><s:property value="price"/></td>
- </tr>
- </s:iterator>
- </tbody>
- </table>
- 7. Thêm trang index.jsp
- 8. Vào web.xml đổi welcome-file thành index.jsp
- 9. Copy example.xml rồi paste tại chỗ, đổi tên lại thành aptechaction.xml
- <package name="vn.aptech.action" namespace="/" extends="struts-default">
- <action name="DisplayAction" class="vn.aptech.action.Display">
- <result name="success">/display.jsp</result>
- </action>
- </package>
- 10. Vào struts.xml thêm
- <include file="aptechaction.xml"/>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement