Thực hành Strust JSF Lab 2

21 199 0
Thực hành Strust JSF Lab 2

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Architecting Applications for the Web Lab 02 Working with Struts Framework Mục tiêu - Hiểu rõ kiến trúc, thành phần, vòng đời Struts Framework - Nắm vững luồng liệu Struts Framework - Tạo ứng dụng đơn giản với Struts Framework - Thao tác Struts Framework với Database Phần I Bài tập step by step Bài 2.1 Import Plugins để sử dụng Struts Framework: - org-netbeans-modules-framework-xwork.nbm - org-netbeans-modules-web-frameworks-struts2.nbm - org-netbeans-modules-web-frameworks-struts2lib-v2_3_15.nbm Tạo project với Struts Framework Netbeans - Nhập vào tên người dùng - Hiển thị: “Xin chào người dùng” Step 1: Tạo project Netbeans giống lab01  Project Name: Lab02  Server: GlassFish Server  Frameworks: Struts IT Research Department @BKAP 2015 Page / 21 Enterprise Application Development in Java EE  Trong đó:  1: Chọn Framework Struts  2: Bỏ chọn Create example page  3: Finish  Cấu trúc ứng dụng sau hoàn thành Step 2: Tạo trang trang view jsp  input.jsp chứa textbox nhập vào tên người dùng IT Research Department @BKAP 2015 Page / 21 Architecting Applications for the Web Input Page  output.jsp hiển thị “Xin chào người dùng” Output Page Xin chào  Lưu ý: Khi submit form input Struts duyệt tìm file struts.xml thẻ action có name tương ứng Step 3: Tạo Action hứng liệu form input.jsp thực nghiệp vụ xử lý liệu trả kết cho struts.xml  Lab02  Source Packages  New  Other  Struts  ActionSupport based Action IT Research Department @BKAP 2015 Page / 21 Enterprise Application Development in Java EE  Trong  1: Tên Action  2: Package chứa Action  3: Finish IT Research Department @BKAP 2015 Page / 21 Architecting Applications for the Web  Code thực nghiệp vụ cho DisplayAction.java package action; import com.opensymphony.xwork2.ActionSupport; /** * * @author Quang */ public class DisplayAction extends ActionSupport { //Khai bao du lieu userName tren form input.jsp private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public DisplayAction() { } //Xu ly du lieu va tra ve SUCCESS = "success" @Override public String execute() throws Exception { return SUCCESS; }  Lưu ý:  Struts định nghĩa sẵn String như:  SUCCESS = “success”  NONE = “none”  ERROR = “error”  INPUT = “input”  LOGIN = “login”  Struts tự động nhận giá trị chuyển đổi kiểu liệu từ view xuống action  Ví dụ trang input.jsp ta có khai báo textbox có name userName, action ta có thuộc tính userName Struts tự động nhận chuyển đổi kiểu liệu giá trị nhập vào textbox userName input.jsp xuống thuộc tính userName action IT Research Department @BKAP 2015 Page / 21 Enterprise Application Development in Java EE Step 4: Cấu hình file struts.xml output.jsp  Các thuộc tính cấu hình file struts.xml  Thẻ action: Chứa thông tin action  Name: Tên Action thực (Có phân biệt hoa thường)  Class: Đường dẫn lớp action  Method: Phương thức action thực (Bài 2.2 thực hiện)  Thẻ Result: Điều hướng chuyển trang dựa kết trả từ action  Name: giá trị String trả từ action Step 5: Cấu hình web.xml struts2 org.apache.struts2.dispatcher.FilterDispatcher struts2 /* 30 IT Research Department @BKAP 2015 Page / 21 Architecting Applications for the Web input.jsp Step 6: Build and Run Application Bài 2.2 Sử dụng Struts Framework thực chức thao tác với Database: - Tạo bảng Catalog có thơng tin sau: - Tạo thủ tục thực tác vụ GetAllCatalog, InsertCatalog, UpdateCatalog, DeleteCatalog - Xây dựng trang jsp, action cấu hình Struts.xml để thực tác vụ Step 1: Tạo bảng Catalog có thông tin Database Struts2DB Step 2: Tạo thủ tục IT Research Department @BKAP 2015 Page / 21 Enterprise Application Development in Java EE  GetAllCatalog  InsertCatalog  UpdateCatalog IT Research Department @BKAP 2015 Page / 21 Architecting Applications for the Web  DeleteCatalog  GetCatalogById Step 3: Tạo Project Web Application, đặt tên Lab02_CRUD sử dụng framework Struts Step 4: Tạo file jsp để thực việc nhập, hiển thị liệu  index.jsp: file welcome-file project Thực việc gọi action GetAllCatalog kết trả thị nơi gọi action băng cách sử dụng thuộc tính executeResult=”true” thẻ action %> List Catalog IT Research Department @BKAP 2015 Page / 21 Enterprise Application Development in Java EE  listCatalog.jsp: file hiển thị danh sách loại sản phẩm sau thực lấy tất liệu loại sản phẩm từ Database File đưa vào phần body file index.jsp Catalog ID Catalog Name Description Action List Catalog Update Delete Add  Lưu ý: thẻ Update set vào request parameter có tên catalogId có giá trị click vào link Update gọi action initUpdate khai báo struts.xml Trong lớp action ta lấy parameter cách get từ HttpServletRequest implement từ interface ServletRequestAware (Sẽ trình bày thêm bên dưới)  insertCatalog.jsp: file jsp chứa form nhập liệu thông tin đối tượng catalog Insert Catalog Insert Catalog IT Research Department @BKAP 2015 Page 10 / 21 Architecting Applications for the Web  updateCatalog.jsp: file jsp chứa form cập nhật thông tin đối tượng catalog Update Catalog Update Catalog  Lưu ý:  name="updateCatalog.catalogId" dùng để lấy giá trị textfield Catalog ID set vào field catalogId đối tượng updateCatalog  value="%{initCatalog.catalogId}" dùng để lấy giá trị field catalogId đối tượng initCatalog vào textfield Catalog ID  error.jsp: file jsp thơng báo lỗi q trình xử lý JSP Page Error In Processing Back Index Step 5: Tạo lớp ConnectionDB.java: tạo connection truy xuất database IT Research Department @BKAP 2015 Page 11 / 21 Enterprise Application Development in Java EE  Lab02_CRUD  Source Packages  RC  New  Other  Java  Java Class  Đặt tên ConnectionDB nằm package util package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @author Quang */ public class ConnectionDB { private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=Struts2DB"; private static final String DB_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String user_db = "sa"; private static final String pass_db = "Gacon1984"; public static Connection getDBConnection() { Connection conn = null; try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(URL, user_db, pass_db); } catch (SQLException ex) { ex.printStackTrace(); } return conn; } Step 6: Tạo đối tượng Catalog (Lớp catalog.java)  Lab02_CRUD  Source Packages  RC  New  Other  Java  Java Class  Đặt tên catalog nằm package entities package entities; /** * * @author Quang */ public class Catalog { private int catalogId; private String catalogName; private String description; public int getCatalogId() { return catalogId; } IT Research Department @BKAP 2015 Page 12 / 21 Architecting Applications for the Web public void setCatalogId(int catalogId) { this.catalogId = catalogId; } public String getCatalogName() { return catalogName; } public void setCatalogName(String catalogName) { this.catalogName = catalogName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } Step 7: Tạo lớp action Struts2  Lab02_CRUD  Source Packages  RC  New  Other  Struts2  ActionSupport based Action  Đặt tên CatalogAction package bkap.action package bkap.action; import static com.opensymphony.xwork2.Action.ERROR; import static com.opensymphony.xwork2.Action.SUCCESS; import com.opensymphony.xwork2.ActionSupport; import entities.Catalog; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import util.ConnectionDB; /** * * @author Quang */ public class CatalogAction extends ActionSupport implements ServletRequestAware { IT Research Department @BKAP 2015 Page 13 / 21 Enterprise Application Development in Java EE //Khai bao doi tuong catalog chua du lieu loai san pham insert private Catalog insertCatalog; //Khai bao doi tuong catalog chua du lieu loai san pham lay tren danh sach de update private Catalog initCatalog; //Khai bao doi tuong catalog chua du lieu loai san pham update private Catalog updateCatalog; //Khai bao danh sach doi tuong loai san pham chua du lieu lay tu database ve private List listCatalog; //Khai bao request xu ly cac yeu cau private HttpServletRequest request; //Khoi tao cac doi tuong public CatalogAction() { insertCatalog = new Catalog(); initCatalog = new Catalog(); updateCatalog = new Catalog(); listCatalog = new ArrayList(); } public Catalog getInsertCatalog() { return insertCatalog; } //Getter and setter cac thuoc tinh public void setInsertCatalog(Catalog insertCatalog) { this.insertCatalog = insertCatalog; } public Catalog getInitCatalog() { return initCatalog; } public void setInitCatalog(Catalog initCatalog) { this.initCatalog = initCatalog; } public Catalog getUpdateCatalog() { return updateCatalog; } public void setUpdateCatalog(Catalog updateCatalog) { this.updateCatalog = updateCatalog; } public List getListCatalog() { return listCatalog; } public void setListCatalog(List listCatalog) { this.listCatalog = listCatalog; } public HttpServletRequest getRequest() { return request; } IT Research Department @BKAP 2015 Page 14 / 21 Architecting Applications for the Web public void setRequest(HttpServletRequest request) { this.request = request; } //Lay request xu ly @Override public void setServletRequest(HttpServletRequest hsr) { this.request = hsr; } //GetAllCatalog public String getAllCatalog() { //Connect Database Connection conn = null; CallableStatement callableStatement = null; try { //Tao Connection conn = ConnectionDB.getDBConnection(); //Goi Procedure callableStatement = conn.prepareCall("{call GetAllCatalog()}"); //Lay du lieu ve ResultSet ResultSet rs = callableStatement.executeQuery(); while (rs.next()) { //Day du lieu vao listCatalog Catalog catalog = new Catalog(); catalog.setCatalogId(rs.getInt("CatalogId")); catalog.setCatalogName(rs.getString("CatalogName")); catalog.setDescription(rs.getString("Description")); listCatalog.add(catalog); } } catch (Exception e) { return ERROR; } finally { if (conn != null) { try { //Dong connection conn.close(); } catch (SQLException ex) { Logger.getLogger(CatalogAction.class.getName()).log(Level.SEVERE, null, ex); } } } return SUCCESS; } //Insert Catalog public String insertCatalog() { Connection conn = null; CallableStatement callableStatement = null; try { //Tao connection voi Database conn = ConnectionDB.getDBConnection(); //Set cac gia tri dau vao cua procedure callableStatement = conn.prepareCall("{call InsertCatalog(?,?)}"); callableStatement.setString(1, this.insertCatalog.getCatalogName()); callableStatement.setString(2, this.insertCatalog.getDescription()); IT Research Department @BKAP 2015 Page 15 / 21 Enterprise Application Development in Java EE //Thuc thi Insert Catalog vao database callableStatement.executeUpdate(); } catch (Exception e) { return ERROR; } finally { if (conn != null) { try { //Dong connection conn.close(); } catch (SQLException ex) { Logger.getLogger(CatalogAction.class.getName()).log(Level.SEVERE, null, ex); } } } return SUCCESS; } //Lay doi tuong can update public String initUpdate() { //Lay Catalog ID cua loai san pham can update int catalogId = Integer.parseInt(request.getParameter("catalogId")); //Lay Catalog theo CatalogId tu Database //Connect Database Connection conn = null; CallableStatement callableStatement = null; try { //Tao Connection conn = ConnectionDB.getDBConnection(); //Goi Procedure callableStatement = conn.prepareCall("{call GetCatalogById(?)}"); //Set cac gia tri dau vao cua procedure callableStatement.setInt(1, catalogId); //Lay du lieu ve ResultSet ResultSet rs = callableStatement.executeQuery(); while (rs.next()) { //Day du lieu vao initCatalog initCatalog.setCatalogId(rs.getInt("CatalogId")); initCatalog.setCatalogName(rs.getString("CatalogName")); initCatalog.setDescription(rs.getString("Description")); } } catch (Exception e) { return ERROR; } finally { if (conn != null) { try { //Dong connection conn.close(); } catch (SQLException ex) { Logger.getLogger(CatalogAction.class.getName()).log(Level.SEVERE, null, ex); } } } return SUCCESS; } //Update Catalog public String updateCatalog() { IT Research Department @BKAP 2015 Page 16 / 21 Architecting Applications for the Web Connection conn = null; CallableStatement callableStatement = null; try { //Tao connection voi Database conn = ConnectionDB.getDBConnection(); //Set cac gia tri dau vao cua procedure callableStatement = conn.prepareCall("{call UpdateCatalog(?,?,?)}"); callableStatement.setInt(1, this.updateCatalog.getCatalogId()); callableStatement.setString(2, this.updateCatalog.getCatalogName()); callableStatement.setString(3, this.updateCatalog.getDescription()); //Thuc thi Update Catalog vao database callableStatement.executeUpdate(); } catch (Exception e) { return ERROR; } finally { if (conn != null) { try { //Dong connection conn.close(); } catch (SQLException ex) { Logger.getLogger(CatalogAction.class.getName()).log(Level.SEVERE, null, ex); } } } return SUCCESS; } //Delete Catalog public String deleteCatalog() { //Lay Catalog ID cua loai san pham can delete int catalogId = Integer.parseInt(request.getParameter("catalogId")); //Connect Database Connection conn = null; CallableStatement callableStatement = null; try { //Tao connection voi Database conn = ConnectionDB.getDBConnection(); //Set cac gia tri dau vao cua procedure callableStatement = conn.prepareCall("{call DeleteCatalog(?)}"); callableStatement.setInt(1, catalogId); //Thuc thi Delete Catalog vao database callableStatement.executeUpdate(); } catch (Exception e) { return ERROR; } finally { if (conn != null) { try { //Dong connection conn.close(); } catch (SQLException ex) { Logger.getLogger(CatalogAction.class.getName()).log(Level.SEVERE, null, ex); } } } return SUCCESS; } IT Research Department @BKAP 2015 Page 17 / 21 Enterprise Application Development in Java EE }  Lưu ý:  Lớp action kế thừa (extends) ActionSupport Struts2  Thực thi (implement) interface ServletRequestAware để lấy parameter lưu request  Khai báo biến request kiểu HttpServletRequest để hứng request ServletRequestAware Step 8: Cấu hình file struts.xml listCatalog.jsp error.jsp index.jsp error.jsp updateCatalog.jsp error.jsp index.jsp error.jsp index.jsp error.jsp IT Research Department @BKAP 2015 Page 18 / 21 Architecting Applications for the Web Step 9: Build and Run ứng dụng IT Research Department @BKAP 2015 Page 19 / 21 Enterprise Application Development in Java EE Phần II Bài tập tự làm Bài 2.1 Thao tác sở liệu với Struts framework - Cho bảng Product có thuộc tính sau: Thuộc tính Kiểu liệu Diễn giải ProductId Int, PK, identity(1,1) Mã sản phẩm ProductName Nvarchar(200) Tên sản phẩm CatalogId Int, FK(Catalog) Mã loại sản phẩm IT Research Department @BKAP 2015 Page 20 / 21 Architecting Applications for the Web Price Float Giá sản phẩm ProductContent Text Mô tả sản phẩm Discount Int Giảm giá Image Nvarchar(100) Link ảnh sản phẩm Created Date Ngày tạo sản phẩm PView Int Lượt xem sản phẩm PStatus Bit Trạng thái sản phẩm - Thực CRUD Insert,Update,Delete,GetAll - Thực tác vụ liệt kê tất sản phẩm theo loại sản phẩm (catalogId), theo số lượng lượng xem sản phẩm (PView) IT Research Department @BKAP 2015 Page 21 / 21 ... Database Connection conn = null; CallableStatement callableStatement = null; try { //Tao Connection conn = ConnectionDB.getDBConnection(); //Goi Procedure callableStatement = conn.prepareCall("{call... conn = null; CallableStatement callableStatement = null; try { //Tao connection voi Database conn = ConnectionDB.getDBConnection(); //Set cac gia tri dau vao cua procedure callableStatement =... Database Connection conn = null; CallableStatement callableStatement = null; try { //Tao Connection conn = ConnectionDB.getDBConnection(); //Goi Procedure callableStatement = conn.prepareCall("{call

Ngày đăng: 07/05/2018, 16:01

Tài liệu cùng người dùng

Tài liệu liên quan