IT Research Department @BKAP 2015 Page 1 / 26 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
Trang 1IT Research Department @BKAP 2015 Page 1 / 26
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 1
Tạo project EJB với Session Bean Stateless có interface là Local làm việc với DataBase EJB
có bảng sau:
Book
Project thực hiện các công việc sau:
- Tạo class Book tương ứng với bảng Book trong CSDL
- Tạo Session Bean Stateless Local gồm các phương thức sau:
+ insertBook: thêm thông tin vào bảng Book
Trang 2+ countBook: Trả về số sách thỏa mãn điều kiện giá sách nằm trong khoảng 200000
và 500000
+ searchByName: Trả về danh sách sách có Title bắt đầu bằng ký tự “S” (Cho phép gọi Asynchronous)
Step 1: Tạo Table Book trong Database EJB và các procedure thực hiện nghiệp vụ
insertBook, countBook, searchByName
Tạo Database EJB và Table Book
CreateDataBaseEJB
go
UseEJB
go
CREATETABLE[dbo].[Book](
[BookID][int]IDENTITY(1,1)NOTNULL,
[Title][nvarchar](200)NOTNULL,
[Author][nvarchar](50)NOTNULL,
[Price][float]NOTNULL,
[Publisher][nvarchar](100)NULL,
[Picture][nvarchar](100)NULL,
CONSTRAINT[PK_Book]PRIMARYKEYCLUSTERED
(
[BookID]ASC
)WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=
ON,ALLOW_PAGE_LOCKS=ON)ON[PRIMARY]
Trang 3IT Research Department @BKAP 2015 Page 3 / 26
SELECT@count=count(*)FROMBookWHEREPriceBETWEEN@price1AND@price2
Step 2: Tạo Project EJB tên Session03_04 với Session Bean là Stateless (tên
S03_04StatelessBean) và Interface là Local (Như đã hướng dẫn ở Lab 01 + 02)
Cấu trúc ứng dụng sau khi hoàn thành
Trang 4Step 3: Tạo lớp Book.java tương ứng với bảng Book trong CSDL (có constructor và get,set)
Session03_04-ejb Source Packages New Other Java Java Class
Trang 5IT Research Department @BKAP 2015 Page 5 / 26
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;
Trang 6}
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;
public interface S03_04StatelessBeanLocal {
String insertBook(String title, String author, float price, String publisher, String picture);
int countBook(float price1, float price2);
List<Book> searchByName(String titleStartWith);
Trang 7IT Research Department @BKAP 2015 Page 7 / 26
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;
conn = DriverManager.getConnection( URL, user_db, pass_db);
} catch (SQLException ex) {
public String insertBook(String title, String author, float price, String publisher, String picture) {
Connection conn = null;
CallableStatement callableStatement = null;
public int countBook(float price1, float price2) {
Connection conn = null;
CallableStatement callableStatement = null;
Trang 8Connection conn = null;
CallableStatement callableStatement = null;
List<Book> listBook = new ArrayList<Book>();
Step 6: Tạo các trang jsp để test các chức năng thực hiện trên Session Bean
Index.jsp: Chọn các chức năng cần test
<%@ pagecontentType="text/html"pageEncoding="UTF-8"%>
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Book Page</title>
</head>
<body>
<h1>List Function Test</h1>
<ahref="insertBook.jsp">Insert Book</a><br>
<ahref="countBook.jsp">Count Book</a><br>
<ahref="searchByName.jsp">Search By Name</a><br>
</body>
Trang 9IT Research Department @BKAP 2015 Page 9 / 26
</html>
insertBook.jsp: Nhập liệu các thông tin Book để Insert
<%@ pagecontentType="text/html"pageEncoding="UTF-8"%>
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Insert Book Page</title>
</head>
<body>
<h1>Insert Book</h1>
<formaction="S03_04Servlet"method="Post">
Title:<inputtype="text"name="title"/><br>
Author:<inputtype="text"name="author"/><br>
Price:<inputtype="text"name="price"/><br>
Publisher:<inputtype="text"name="publisher"/><br>
Picture:<inputtype="text"name="picture"/><br><br>
<inputtype="submit"name="insertBook"value="InsertBook">
</form>
</body>
</html>
countBook.jsp: Nhập đếm số Book có mức giá từ bao nhiêu đến bao nhiêu
<%@ pagecontentType="text/html"pageEncoding="UTF-8"%>
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Count Book Page</title>
</head>
<body>
<h1>Count Book</h1>
<formaction="S03_04Servlet"method="Post">
Price From:<inputtype="text"name="price1"/><br>
Price To:<inputtype="text"name="price2"/><br><br>
<inputtype="submit"name="countBook"value="CountBook">
</form>
</body>
</html>
searchByName.jsp: Nhập chữ bắt đầu của title Book muốn tìm kiếm
<%@ pagecontentType="text/html"pageEncoding="UTF-8"%>
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Search By Name Page</title>
</head>
<body>
<h1>Search By Name</h1>
<formaction="S03_04Servlet"method="Post">
Title Start With:<inputtype="text"name="titleStartWith"/><br><br>
<inputtype="submit"name="titleStartWith"value="Search">
</form>
</body>
Trang 10</html>
listBook.jsp: Hiển thị danh sách Book
<%@ pageimport="java.util.ArrayList"%>
<%@ pageimport="entities.Book"%>
<%@ pageimport="java.util.List"%>
<%@ pagecontentType="text/html"pageEncoding="UTF-8"%>
<%@ tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c" %>
<%
Object sessionObj = request.getSession().getAttribute("listBook");
List<Book> listBook = new ArrayList<Book>();
listBook = (List<Book>) sessionObj;
%>
<!DOCTYPEhtml>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>List Books</title>
</head>
<body>
<divalign="center">
<tableborder="1"cellpadding="5">
<caption><h2>List of Books</h2></caption>
<td>< c:outvalue="${book.bookID}" /></td>
<td>< c:outvalue="${book.title}" /></td>
<td>< c:outvalue="${book.author}" /></td>
<td>< c:outvalue="${book.price}" /></td>
<td>< c:outvalue="${book.publisher}" /></td>
<td>< c:outvalue="${book.picture}" /></td>
Step 7: Tạo servlet S03_04Servlet trong thư mục servlet trên Session03_04-war Sau đó gọi
S03_04StatelessBean (Như bài Lab 01 + 02 đã hướng dẫn)
package servlet;
import bean.S03_04StatelessBeanLocal;
import entities.Book;
import java.io.IOException;
Trang 11IT Research Department @BKAP 2015 Page 11 / 26
* @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 */
if (request.getParameter("insertBook")!=null) {
String title = request.getParameter("title");
String author = request.getParameter("author");
float price = Float.parseFloat(request.getParameter("price"));
String publisher = request.getParameter("publisher");
String picture = request.getParameter("picture");
String returnStr = s03_04StatelessBean.insertBook(title, author, price, publisher, picture);
}else if (request.getParameter("countBook")!=null) {
float price1 = Float.parseFloat(request.getParameter("price1"));
float price2 = Float.parseFloat(request.getParameter("price2"));
int returncount = s03_04StatelessBean.countBook(price1, price2);
out.println("<h1>Count Book: "+returncount+"</h1>");
}
else {
Trang 12String titleStartWith = request.getParameter("titleStartWith");
List<Book> listBook = s03_04StatelessBean.searchByName(titleStartWith);
request.setAttribute("listBook", listBook);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/listBook.jsp");
* @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 {
* @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 {
public String getServletInfo() {
return "Short description";
Trang 13IT Research Department @BKAP 2015 Page 13 / 26
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>S03_04Servlet</servlet-name>
<servlet-class>servlet.S03_04Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>S03_04Servlet</servlet-name>
<url-pattern>/S03_04Servlet</url-pattern>
Step 9: Add sqljdbc4.jar vào thư mục Libraries của Session03_04-ejb
Session03_04-ejb Libraries Add JAR/Folder chọn đến sqljdbc4.jar
Step 10: Build, Deploy and Run Application
Insert Book
Trang 14 Count Book
Trang 15IT Research Department @BKAP 2015 Page 15 / 26
Search By Name
Trang 16Bài 2
Phát triển tiếp bài 1, tạo Session Bean Stateful với interface là Remote gồm các phương thức sau
- getBooks(): Trả về tất cả sách
- addBasket(BookID): Lưu BookID vào một List mỗi khi addBasket được gọi
- getBasket(): Trả về List of Book
Step 1: Tạo các procedure thực hiện nghiệp vụ lấy tất cả sách trong bảng Book
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 trong CSDL (có constructor và get,set)
trong package entity của interface Stateful_Interface
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;
Trang 17IT Research Department @BKAP 2015 Page 17 / 26
this.picture = picture;
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