Tải bản đầy đủ (.pdf) (26 trang)

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

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.45 MB, 26 trang )

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 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
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 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
IT Research Department

@BKAP 2015

Page 1 / 26


Enterprise Application Development in Java EE
+ 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
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 2 / 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 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

IT Research Department

@BKAP 2015

Page 3 / 26


Enterprise Application Development in Java EE
Step 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

IT Research Department

@BKAP 2015

Page 4 / 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 5 / 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 các phương thức nghiệp vụ trên 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<Book> searchByName(String titleStartWith);
}

Step 5: Thực thi các phương thức nghiệp vụ trên 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 6 / 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 7 / 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<Book> searchByName(String titleStartWith) {
String st = titleStartWith + "%";
Connection conn = null;

CallableStatement callableStatement = null;
List<Book> listBook = new ArrayList<Book>();
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 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
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Page</title>
</head>
<body>

List Function Test


<a href="insertBook.jsp">Insert Book</a>

<a href="countBook.jsp">Count Book</a>

<a href="searchByName.jsp">Search By Name</a>

</body>

IT Research Department

@BKAP 2015

Page 8 / 26


Enterprise Application Development in Java EE
</html>

 insertBook.jsp: Nhập liệu các thông tin Book để Insert
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Book Page</title>
</head>
<body>

Insert Book


<form action="S03_04Servlet" method="Post">
Title:<input type="text" name="title"/>

Author:<input type="text" name="author"/>

Price:<input type="text" name="price"/>

Publisher:<input type="text" name="publisher"/>

Picture:<input type="text" name="picture"/>


<input type="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
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Count Book Page</title>
</head>
<body>

Count Book


<form action="S03_04Servlet" method="Post">
Price From:<input type="text" name="price1"/>

Price To:<input type="text" name="price2"/>


<input type="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
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search By Name Page</title>
</head>
<body>

Search By Name


<form action="S03_04Servlet" method="Post">
Title Start With:<input type="text" name="titleStartWith"/>


<input type="submit" name="titleStartWith" value="Search">
</form>
</body>

IT Research Department

@BKAP 2015

Page 9 / 26


Enterprise Application Development in Java EE
</html>

 listBook.jsp: Hiển thị danh sách Book
<%@page import="java.util.ArrayList"%>
<%@page import="entities.Book"%>
<%@page import="java.util.List"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri=" prefix="c" %>
<%
Object sessionObj = request.getSession().getAttribute("listBook");
List<Book> listBook = new ArrayList<Book>();
listBook = (List<Book>) sessionObj;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Books</title>
</head>
<body>
<div align="center">
<table border="1" cellpadding="5">
<caption>

List of Books

</caption>
<tr>
<th>BookID</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Publisher</th>
<th>Picture</th>
</tr>
<c:forEach var="book" items="${listBook}">
<tr>
<td><c:out value="${book.bookID}" /></td>
<td><c:out value="${book.title}" /></td>
<td><c:out value="${book.author}" /></td>

<td><c:out value="${book.price}" /></td>
<td><c:out value="${book.publisher}" /></td>
<td><c:out value="${book.picture}" /></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>

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;

IT Research Department

@BKAP 2015

Page 10 / 26


Enterprise Application Development in Java EE
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
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 S03_04Servlet extends HttpServlet {
@EJB
private S03_04StatelessBeanLocal s03_04StatelessBean;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @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("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet S03_04Servlet</title>");
out.println("</head>");
out.println("<body>");

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);
if (returnStr.equals("Success")) {
out.println("

Insert Book Success

");
} else {
out.println("

Insert Book Error

");
}
}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("

Count Book: "+returncount+"

");
}
else {

IT Research Department

@BKAP 2015

Page 11 / 26


Enterprise Application Development in Java EE
String titleStartWith = request.getParameter("titleStartWith");
List<Book> listBook = s03_04StatelessBean.searchByName(titleStartWith);

request.setAttribute("listBook", listBook);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/listBook.jsp");
rd.forward(request, response);
}
out.println("</body>");
out.println("</html>");
}
}
//
/**
* Handles the HTTP <code>GET</code> 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 <code>POST</code> 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";
}// </editor-fold>
}

Step 8: Cấu hình web.xml để trang index.jsp làm trang welcome-file-list
Web.xml
<?xml version="1.0" encoding="UTF-8"?>

IT Research Department

@BKAP 2015

Page 12 / 26


Enterprise Application Development in Java EE
<web-app version="3.1" xmlns=" />xmlns:xsi=" xsi:schemaLocation=" /> /><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>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

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

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 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
 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 trong CSDL (có constructor và get,set)
trong package entity của 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 các 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<Book> getAllBook();
void addBasket(int bookID);
List<Integer> getBasket();
List<Book> getListBook();

}

Step 6: Thực thi các 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<Integer> listInteger;
private List<Book> listBook;
public StatefulSessionBean() {
listBook = new ArrayList<Book>();
listInteger = new ArrayList<Integer>();


IT Research Department

@BKAP 2015

Page 19 / 26


Enterprise Application Development in Java EE
}
public List<Integer> getListInteger() {
return listInteger;
}
public void setListInteger(List<Integer> listInteger) {
this.listInteger = listInteger;
}
@Override
public List<Book> getListBook() {
return listBook;
}
public void setListBook(List<Book> 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<Book> getAllBook() {
Connection conn = null;
listBook = new ArrayList<Book>();
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<Integer> getBasket() {
return listInteger;
}
}

Step 7: Xây dựng các trang jsp để test các nghiệp vụ đã xây dựng
 Session03_04-war  Web Pages  JSP
 getAllBook.jsp: Hiển thị tất cả các sách và danh sách các BookID đã được addBasket
<%@page import="java.util.ArrayList"%>
<%@page import="entity.Book"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri=" prefix="c" %>
<%
Object sessionObj = request.getSession().getAttribute("listBook");

List<Book> listBook = new ArrayList<Book>();
listBook = (List<Book>) sessionObj;
Object sessionObjInt = request.getSession().getAttribute("listInteger");
List<Integer> listInteger = new ArrayList<Integer>();
listInteger = (List<Integer>) sessionObjInt;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Books</title>
</head>
<body>
<div>
<table border="1" cellpadding="5">
<caption>

List of Books

</caption>
<tr>
<th>BookID</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Publisher</th>
<th>Picture</th>
<th>Action</th>
</tr>
<c:forEach var="book" items="${listBook}">
<tr>
<td><c:out value="${book.bookID}" /></td>

IT Research Department


@BKAP 2015

Page 21 / 26


Enterprise Application Development in Java EE
<td><c:out value="${book.title}" /></td>
<td><c:out value="${book.author}" /></td>
<td><c:out value="${book.price}" /></td>
<td><c:out value="${book.publisher}" /></td>
<td><c:out value="${book.picture}" /></td>
<td>
<a href="StatefulServlet?bookID=${book.bookID}"> Add Basket </a>
</td>
</tr>
</c:forEach>
</table>
</div>
<div>

List Books were added Basket:
<c:forEach var="bookID" items="${listInteger}">
<c:out value="${bookID}" />;
</c:forEach>


</div>
</body>
</html>

Step 7: Xây dựng Servlet gọi Session Bean để test các 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 <code>GET</code> and <code>POST</code>
* 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("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet StatefulServlet</title>");
out.println("</head>");
out.println("<body>");
if (request.getParameter("bookID") != null) {
int bookID = Integer.parseInt(request.getParameter("bookID"));
statefulSessionBean.addBasket(bookID);
List<Book> listBook = statefulSessionBean.getListBook();
List<Integer> listInteger = statefulSessionBean.getBasket();
request.setAttribute("listBook", listBook);
request.setAttribute("listInteger", listInteger);

RequestDispatcher rd = getServletContext().getRequestDispatcher("/getAllBook.jsp");
rd.forward(request, response);
} else {
List<Book> listBook = statefulSessionBean.getAllBook();
request.setAttribute("listBook", listBook);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/getAllBook.jsp");
rd.forward(request, response);
}
out.println("</body>");
out.println("</html>");
}
}
//
/**
* Handles the HTTP <code>GET</code> 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 <code>POST</code> 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";
}// </editor-fold>
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 khi hoàn thành

IT Research Department

@BKAP 2015

Page 25 / 26


×