Thực hành EJB (Enterprise Java Bean) Lab 3 + 4

26 259 1
Thực hành EJB (Enterprise Java Bean) Lab 3 + 4

Đ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

Enterprise Application Development in Java EE Lab 03 + 04 Session Beans Stateful Session Beans Mục tiêu - Thao tác session bean Stateless với DataBase - Thao tác session bean Stateful với DataBase Phần I Bài tập step by step Bài Tạo project EJB với Session Bean Stateless có interface Local làm việc với DataBase EJB có bảng sau: Book Column Data Type Characteristic Description BookID Int PK, Auto Increment Mã sách Title Nvarchar(200) Not Null Tiêu đề sách Author Nvarchar(50) Not Null Tác giả Price Float Not Null Giá sách Publisher Nvarchar(100) Allow Null Nhà phát hành Picture Nvarchar(100) Allow Null Ảnh sách Project thực công việc sau: - Tạo class Book tương ứng với bảng Book CSDL - Tạo Session Bean Stateless Local gồm phương thức sau: + insertBook: thêm thông tin vào bảng Book IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE + countBook: Trả số sách thỏa mãn điều kiện giá sách nằm khoảng 200000 500000 + searchByName: Trả danh sách sách có Title bắt đầu ký tự “S” (Cho phép gọi Asynchronous) Step 1: Tạo Table Book Database EJB procedure thực nghiệp vụ insertBook, countBook, searchByName  Tạo Database EJB Table Book Create DataBase EJB go Use EJB go CREATE TABLE [dbo].[Book]( [BookID] [int] IDENTITY(1,1) NOT NULL, [Title] [nvarchar](200) NOT NULL, [Author] [nvarchar](50) NOT NULL, [Price] [float] NOT NULL, [Publisher] [nvarchar](100) NULL, [Picture] [nvarchar](100) NULL, CONSTRAINT [PK_Book] PRIMARY KEY CLUSTERED ( [BookID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]  Tạo Procedure insertBook USE EJB GO CREATE PROCEDURE insertBook @title nvarchar(200), @author nvarchar(50), @price float, @publisher nvarchar(100), @picture nvarchar(100) AS BEGIN INSERT INTO Book VALUES (@title,@author,@price,@publisher,@picture) END GO  Tạo Procedure countBook USE EJB GO CREATE PROCEDURE countBook @price1 float, @price2 float, @count int OUTPUT AS BEGIN IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE SELECT @count = count(*) FROM Book WHERE Price BETWEEN @price1 AND @price2 END  Tạo Procedure searchByName USE EJB GO CREATE PROCEDURE searchByName @titleStartWith nvarchar(2) AS BEGIN SELECT * FROM Book WHERE Title like @titleStartWith END GO Step 2: Tạo Project EJB tên Session03_04 với Session Bean Stateless (tên S03_04StatelessBean) Interface Local (Như hướng dẫn Lab 01 + 02)  Cấu trúc ứng dụng sau hoàn thành IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE Step 3: Tạo lớp Book.java tương ứng với bảng Book CSDL (có constructor get,set)  Session03_04-ejb  Source Packages  New  Other  JavaJava Class IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE  Book.java package entities; /** * * @author admin */ public class Book { private int bookID; private String title; private String author; private float price; private String publisher; private String picture; public Book(int bookID, String title, String author, float price, String publisher, String picture) { this.bookID = bookID; this.title = title; this.author = author; this.price = price; this.publisher = publisher; this.picture = picture; } public int getBookID() { return bookID; } public void setBookID(int bookID) { this.bookID = bookID; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } } Step 4: Khai báo phương thức nghiệp vụ S03_04StatelessBeanLocal S03_04StatelessBeanLocal.java package bean; import entities.Book; import java.util.List; import javax.ejb.Local; /** * * @author admin */ @Local public interface S03_04StatelessBeanLocal { String insertBook(String title, String author, float price, String publisher, String picture); int countBook(float price1, float price2); List searchByName(String titleStartWith); } Step 5: Thực thi phương thức nghiệp vụ S03_04StatelessBean S03_04StatelessBean.java package bean; import entities.Book; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE /** * * @author admin */ @Stateless public class S03_04StatelessBean implements S03_04StatelessBeanLocal { private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=EJB"; private static final String DB_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String user_db = "sa"; private static final String pass_db = "1234$"; private 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; } @Override public String insertBook(String title, String author, float price, String publisher, String picture) { Connection conn = null; CallableStatement callableStatement = null; try { conn = getDBConnection(); String insertBook = "{call insertBook(?,?,?,?,?)}"; callableStatement = conn.prepareCall(insertBook); callableStatement.setString(1, title); callableStatement.setString(2, author); callableStatement.setFloat(3, price); callableStatement.setString(4, publisher); callableStatement.setString(5, picture); callableStatement.executeUpdate(); return "Success"; } catch (Exception e) { e.printStackTrace(); return "error"; } } @Override public int countBook(float price1, float price2) { Connection conn = null; CallableStatement callableStatement = null; int countB = 0; try { conn = getDBConnection(); String countBook = "{call countBook(?,?,?)}"; IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE callableStatement = conn.prepareCall(countBook); callableStatement.setFloat(1, price1); callableStatement.setFloat(2, price2); callableStatement.registerOutParameter(3, Types.INTEGER); callableStatement.execute(); countB = callableStatement.getInt(3); } catch (Exception e) { e.printStackTrace(); } return countB; } @Override public List searchByName(String titleStartWith) { String st = titleStartWith + "%"; Connection conn = null; CallableStatement callableStatement = null; List listBook = new ArrayList(); try { conn = getDBConnection(); String searchByName = "{call searchByName(?)}"; callableStatement = conn.prepareCall(searchByName); callableStatement.setString(1, st); ResultSet rs = callableStatement.executeQuery(); while (rs.next()) { Book book = new Book(); book.setBookID(rs.getInt("BookID")); book.setTitle(rs.getString("Title")); book.setAuthor(rs.getString("Author")); book.setPrice(rs.getFloat("Price")); book.setPublisher(rs.getString("Publisher")); book.setPicture(rs.getString("Picture")); listBook.add(book); } } catch (Exception e) { e.printStackTrace(); } return listBook; } } Step 6: Tạo trang jsp để test chức thực Session Bean  Index.jsp: Chọn chức cần test Book Page List Function Test Insert Book Count Book Search By Name IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE  insertBook.jsp: Nhập liệu thông tin Book để Insert Insert Book Page Insert Book Title: Author: Price: Publisher: Picture:  countBook.jsp: Nhập đếm số Book có mức giá từ đến Count Book Page Count Book Price From: Price To:  searchByName.jsp: Nhập chữ bắt đầu title Book muốn tìm kiếm Search By Name Page Search By Name Title Start With: IT Research Department @BKAP 2015 Page / 26 Enterprise Application Development in Java EE  listBook.jsp: Hiển thị danh sách Book List Books List of Books BookID Title Author Price Publisher Picture Step 7: Tạo servlet S03_04Servlet thư mục servlet Session03_04-war Sau gọi S03_04StatelessBean (Như Lab 01 + 02 hướng dẫn) package servlet; import bean.S03_04StatelessBeanLocal; import entities.Book; import java.io.IOException; IT Research Department @BKAP 2015 Page 10 / 26 Enterprise Application Development in Java EE String titleStartWith = request.getParameter("titleStartWith"); List listBook = s03_04StatelessBean.searchByName(titleStartWith); request.setAttribute("listBook", listBook); RequestDispatcher rd = getServletContext().getRequestDispatcher("/listBook.jsp"); rd.forward(request, response); } out.println(""); out.println(""); } } // /** * Handles the HTTP GET method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// } Step 8: Cấu hình web.xml để trang index.jsp làm trang welcome-file-list Web.xml IT Research Department @BKAP 2015 Page 12 / 26 Enterprise Application Development in Java EE S03_04Servlet servlet.S03_04Servlet S03_04Servlet /S03_04Servlet 30 index.jsp Step 9: Add sqljdbc4.jar vào thư mục Libraries Session03_04-ejb  Session03_04-ejb  Libraries  Add JAR/Folder  chọn đến sqljdbc4.jar Step 10: Build, Deploy and Run Application  Insert Book IT Research Department @BKAP 2015 Page 13 / 26 Enterprise Application Development in Java EE  Count Book IT Research Department @BKAP 2015 Page 14 / 26 Enterprise Application Development in Java EE  Search By Name IT Research Department @BKAP 2015 Page 15 / 26 Enterprise Application Development in Java EE Bài Phát triển tiếp 1, tạo Session Bean Stateful với interface Remote gồm phương thức sau - getBooks(): Trả tất sách - addBasket(BookID): Lưu BookID vào List addBasket gọi - getBasket(): Trả List of Book Step 1: Tạo procedure thực nghiệp vụ lấy tất sách bảng Book  getAllBook USE EJB GO CREATE PROCEDURE getAllBook AS BEGIN SELECT * FROM Book END GO Step 2: Tạo Interface Stateful_Interface (Như Lab 01 + 02) Step 3: Tạo lớp Book.java tương ứng với bảng Book CSDL (có constructor get,set) package entity interface Stateful_Interface Book.java package entity; /** * * @author admin */ public class Book { private int bookID; private String title; private String author; private float price; private String publisher; private String picture; public Book(int bookID, String title, String author, float price, String publisher, String picture) { this.bookID = bookID; this.title = title; this.author = author; this.price = price; this.publisher = publisher; IT Research Department @BKAP 2015 Page 16 / 26 Enterprise Application Development in Java EE this.picture = picture; } public Book() { } public int getBookID() { return bookID; } public void setBookID(int bookID) { this.bookID = bookID; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } } Step 4: Tạo Session Bean Statefull với interface Remote tới interface Stateful_Interface IT Research Department @BKAP 2015 Page 17 / 26 Enterprise Application Development in Java EE  Session03_04-ejb  New  Other Enterprise JavaBeans  Session Bean IT Research Department @BKAP 2015 Page 18 / 26 Enterprise Application Development in Java EE Step 5: Khai báo phương thức nghiệp vụ getBook, addBasket, getBasket interface Remote StatefulSessionBeanRemote.java package bean; import entity.Book; import java.util.List; import javax.ejb.Remote; /** * * @author admin */ @Remote public interface StatefulSessionBeanRemote { List getAllBook(); void addBasket(int bookID); List getBasket(); List getListBook(); } Step 6: Thực thi nghiệp vụ Session Bean StatefulSessionBean.java package bean; import entity.Book; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateful; /** * * @author admin */ @Stateful public class StatefulSessionBean implements StatefulSessionBeanRemote { private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=EJB"; private static final String DB_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String user_db = "sa"; private static final String pass_db = "1234$"; private List listInteger; private List listBook; public StatefulSessionBean() { listBook = new ArrayList(); listInteger = new ArrayList(); IT Research Department @BKAP 2015 Page 19 / 26 Enterprise Application Development in Java EE } public List getListInteger() { return listInteger; } public void setListInteger(List listInteger) { this.listInteger = listInteger; } @Override public List getListBook() { return listBook; } public void setListBook(List listBook) { this.listBook = listBook; } private 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; } @Override public List getAllBook() { Connection conn = null; listBook = new ArrayList(); CallableStatement callableStatement = null; try { conn = getDBConnection(); String getAllBook = "{call getAllBook()}"; callableStatement = conn.prepareCall(getAllBook); ResultSet rs = callableStatement.executeQuery(); while (rs.next()) { Book book = new Book(); book.setBookID(rs.getInt("BookID")); book.setTitle(rs.getString("Title")); book.setAuthor(rs.getString("Author")); book.setPrice(rs.getFloat("Price")); book.setPublisher(rs.getString("Publisher")); book.setPicture(rs.getString("Picture")); listBook.add(book); } } catch (Exception e) { e.printStackTrace(); } IT Research Department @BKAP 2015 Page 20 / 26 Enterprise Application Development in Java EE return listBook; } @Override public void addBasket(int bookID) { listInteger.add(bookID); } @Override public List getBasket() { return listInteger; } } Step 7: Xây dựng trang jsp để test nghiệp vụ xây dựng  Session03_04-war  Web Pages  JSP  getAllBook.jsp: Hiển thị tất sách danh sách BookID addBasket List Books List of Books BookID Title Author Price Publisher Picture Action IT Research Department @BKAP 2015 Page 21 / 26 Enterprise Application Development in Java EE Add Basket List Books were added Basket: ; Step 7: Xây dựng Servlet gọi Session Bean để test nghiệp vụ xây dựng  Session03_04-war  Source Packages  servlet  StatefulServlet  StatefulServlet.java package servlet; import bean.StatefulSessionBeanRemote; import entity.Book; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author admin */ public class StatefulServlet extends HttpServlet { StatefulSessionBeanRemote statefulSessionBean = lookupStatefulSessionBeanRemote(); /** * Processes requests for both HTTP GET and POST * methods IT Research Department @BKAP 2015 Page 22 / 26 Enterprise Application Development in Java EE * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here You may use following sample code */ out.println(""); out.println(""); out.println(""); out.println("Servlet StatefulServlet"); out.println(""); out.println(""); if (request.getParameter("bookID") != null) { int bookID = Integer.parseInt(request.getParameter("bookID")); statefulSessionBean.addBasket(bookID); List listBook = statefulSessionBean.getListBook(); List listInteger = statefulSessionBean.getBasket(); request.setAttribute("listBook", listBook); request.setAttribute("listInteger", listInteger); RequestDispatcher rd = getServletContext().getRequestDispatcher("/getAllBook.jsp"); rd.forward(request, response); } else { List listBook = statefulSessionBean.getAllBook(); request.setAttribute("listBook", listBook); RequestDispatcher rd = getServletContext().getRequestDispatcher("/getAllBook.jsp"); rd.forward(request, response); } out.println(""); out.println(""); } } // /** * Handles the HTTP GET method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** IT Research Department @BKAP 2015 Page 23 / 26 Enterprise Application Development in Java EE * Handles the HTTP POST method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// private StatefulSessionBeanRemote lookupStatefulSessionBeanRemote() { try { Context c = new InitialContext(); return (StatefulSessionBeanRemote) c.lookup("java:global/Session03_04/Session03_04ejb/StatefulSessionBean!bean.StatefulSessionBeanRemote"); } catch (NamingException ne) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne); throw new RuntimeException(ne); } } } IT Research Department @BKAP 2015 Page 24 / 26 Enterprise Application Development in Java EE  Cấu trúc ứng dụng sau hoàn thành IT Research Department @BKAP 2015 Page 25 / 26 Enterprise Application Development in Java EE Step 8: Build, Deploy and Run Application Phần II Bài Tập Tự Làm Phát triển tiếp tập hướng dẫn Step by Step, Thêm chức sau: - Cập nhật thông tin Book - Xóa thơng tin Book - Tìm kiếm sách theo Title Publisher IT Research Department @BKAP 2015 Page 26 / 26 ... servlet S 03_ 04Servlet thư mục servlet Session 03_ 04- war Sau gọi S 03_ 04StatelessBean (Như Lab 01 + 02 hướng dẫn) package servlet; import bean.S 03_ 04StatelessBeanLocal; import entities.Book; import java. io.IOException;... Step 5: Thực thi phương thức nghiệp vụ S 03_ 04StatelessBean S 03_ 04StatelessBean .java package bean; import entities.Book; import java. sql.CallableStatement; import java. sql.Connection; import java. sql.DriverManager;... picture; } } Step 4: Khai báo phương thức nghiệp vụ S 03_ 04StatelessBeanLocal S 03_ 04StatelessBeanLocal .java package bean; import entities.Book; import java. util.List; import javax .ejb. Local; /**

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

Từ khóa liên quan

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

Tài liệu liên quan