IT Research Department @BKAP 2015 Page 1 / 18Lab 05 Introduction to JavaServerFaces Mục tiêu - Cách tạo ứng dụng Java Web với framework JavaServerFaces JSF - Hiểu rõ các thành phần và
Trang 1IT Research Department @BKAP 2015 Page 1 / 18
Lab 05 Introduction to JavaServerFaces Mục tiêu
- Cách tạo ứng dụng Java Web với framework JavaServerFaces (JSF)
- Hiểu rõ các thành phần và tương tác các thành phần trong JSF
- Nắm vững vòng đời trong JSF
- Tạo project JSF thực hiện các nghiệp vụ cơ bản Insert, Update, Delete, GetAll
- Nắm vững cách validator, converter và các message validator, converter
Phần I Bài tập step by step
Bài 5.1
Tạo CSDL tên JSFDataBase có bảng sau :
Catalog
Increment
Mã loại sản phẩm
phẩm
phẩm
Tạo các thủ tục thực hiện các nghiệp vụ cơ bản Insert, Update, Delete, GetAll với bảng Catalog
Trang 2Step 3: Tạo các thủ tục thực hiện các nghiệp vụ cơ bản Insert, Update, Delete, GetAll
GetAllCatalog
InsertCatalog
UpdateCatalog
Trang 3IT Research Department @BKAP 2015 Page 3 / 18
DeleteCatalog
Bài 5.2
Tạo Project Java Web Application với JavaServerFaces có tên là JSFCRUD
Tạo các thành phần của ứng dụng JSF
Tạo lớp kết nối với Database JSFDataBase
Step 1: Tạo Project JSF có tên là JSFCRUD
File New Project Java Web Web Application
Trang 5IT Research Department @BKAP 2015 Page 5 / 18
Cấu trúc ứng dụng sau khi hoàn thành
Trang 6Step 2: Tạo các thành phần của ứng dụng JSFCRUD
Tạo file JSF Faces Configuration
JSFCRUD New Other JavaServer Faces JSF Faces Configuration
Trang 7IT Research Department @BKAP 2015 Page 7 / 18
File faces-config.xml sau khi tạo xong sẽ ở trong thư mục WEB-INF
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
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-facesconfig_2_2.xsd">
</faces-config>
Tạo file ManagedBean có tên là CatalogManagedBean trong package mangagedBean
Source Packages New Other JavaServer Faces JSF Managed Bean
Trang 8 Sau khi tạo thành CatalogManagedBean sẽ được khai báo tự động trong
face-config.xml
Trang 9IT Research Department @BKAP 2015 Page 9 / 18
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
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-facesconfig_2_2.xsd">
<managed-bean>
<description>This is Managed Bean of modul Catalog</description>
<managed-bean-name>catalogManagedBean</managed-bean-name>
<managed-bean-class>managedBean.CatalogManagedBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
Tạo lớp kết nối với Database JSFDatabase
Tạo một lớp Java có tên ConnectDB.java trong package util
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author admin
*/
public class ConnectDB {
private static final String URL="jdbc:sqlserver://localhost:1433;databaseName=JSFDataBase";
private static final String DB_DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String user = "sa";
private static final String password = "1234$";
public static Connection getDBConnection(){
Connection conn = null;
try {
Class.forName(DB_DRIVER);
try {
conn = DriverManager.getConnection(URL, user, password);
} catch (SQLException ex) {
Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
}
Cấu trúc ứng dụng sau khi hoàn thành
Trang 10Bài 5.3
Tạo thực thể Catalog có các thuộc tính như trong bảng Catalog
Code các chức năng cơ bản Insert, Update, Delete, GetAll trong lớp
CatalogManagedBean
Xây dựng các giao diện UI để thực hiện các tác vụ cơ bản
Step 1: Tạo lớp java (Catalog.java) thể hiện các thuộc tính của thực thể Catalog trong
package entities
package entities;
/**
*
* @author admin
*/
public class Catalog {
private int catalogId;
private String catalogName;
private String description;
public int getCatalogId() {
return catalogId;
}
public void setCatalogId(int catalogId) {
this.catalogId = catalogId;
}
Trang 11IT Research Department @BKAP 2015 Page 11 / 18
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 2: Code các chức năng cơ bản Insert, Update, Delete, GetAll trong
CatalogManagedBean.java
package managedBean;
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.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import util.ConnectDB;
/**
*
* @author admin
*/
public class CatalogManagedBean {
//Doi tuong catalog can update
private Catalog catalogUpdate;
//Doi tuong catalog can Insert
private Catalog catalogInsert;
/**
* Creates a new instance of CatalogManagedBean
*/
public CatalogManagedBean() {
//Khoi tao cac doi tuong
catalogUpdate = new Catalog();
catalogInsert = new Catalog();
}
Trang 12
//Add du lieu vao listCatalog
Catalog catalogGet = new Catalog();
catalogGet.setCatalogId(rs.getInt("CatalogId"));
catalogGet.setCatalogName(rs.getString("CatalogName"));
catalogGet.setDescription(rs.getString("Description"));
listCatalog.add(catalogGet);
}
} catch (SQLException ex) {
Logger.getLogger(CatalogManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
return listCatalog;
}
//Phuong thuc insert catalog vao Database
public void insertCatalog() {
Connection conn = null;
CallableStatement callableStatement = null;
try {
//Khoi tao connection
conn = ConnectDB.getDBConnection();
callableStatement = conn.prepareCall("{call InsertCatalog(?,?)}");
} catch (SQLException ex) {
Logger.getLogger(CatalogManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
try {
//Set du lieu vao callableStatement de insert vao database
callableStatement.setString(1, this.catalogInsert.getCatalogName());
callableStatement.setString(2, this.catalogInsert.getDescription());
//Insert Database
callableStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(CatalogManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Phuong thuc lay du lieu catalog can Update
public void initUpdate() {
//Danh sach cac Catalog
List<Catalog> listCatalog = getAllCatalog();
//Khoi tao FaceContext
FacesContext fc = FacesContext.getCurrentInstance();
//Khoi tao request xu ly
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
//Lay parameter catalogId co trong request
Trang 13IT Research Department @BKAP 2015 Page 13 / 18
int catalogId = Integer.parseInt(request.getParameter("catalogId"));
for (Catalog catalog : listCatalog) {
if (catalog.getCatalogId() == catalogId) {
//Lay catalog can update vao catalogUpdate
this.catalogUpdate = catalog;
break;
}
}
}
//Phuong thuc thuc hien update Catalog
public void updateCatalog() {
Connection conn = null;
CallableStatement callableStatement = null;
try {
//Khoi tao connection
conn = ConnectDB.getDBConnection();
//Goi thu tuc UpdateCatalog
callableStatement = conn.prepareCall("{call UpdateCatalog(?,?,?)}");
} catch (SQLException ex) {
Logger.getLogger(CatalogManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
try {
//Set du lieu vao callableStatement
callableStatement.setInt(1, this.catalogUpdate.getCatalogId());
callableStatement.setString(2, this.catalogUpdate.getCatalogName());
callableStatement.setString(3, this.catalogUpdate.getDescription());
//Thuc hien update
callableStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(CatalogManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void deleteCatalog() {
//Khoi tao FaceContext
FacesContext fc = FacesContext.getCurrentInstance();
//Khoi tao request xu ly
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
//Lay parameter catalogId co trong request
int catalogId = Integer.parseInt(request.getParameter("catalogId"));
Connection conn = null;
CallableStatement callableStatement = null;
try {
//Khoi tao connection
conn = ConnectDB.getDBConnection();
//Goi thu tuc DeleteCatalog
callableStatement = conn.prepareCall("{call DeleteCatalog(?)}");
} catch (SQLException ex) {
Logger.getLogger(CatalogManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
try {
//Set du lieu vao callableStatement
callableStatement.setInt(1, catalogId);
//Thuc hien Delete
Trang 14}
public Catalog getCatalogInsert() {
return catalogInsert;
}
public void setCatalogInsert(Catalog catalogInsert) {
this.catalogInsert = catalogInsert;
}
}
Step 3: Xây dựng các màn hình UI thực hiện các tác vụ cơ bản
listCatalog.xhtml: File xhtml chứa tất cả danh sách các catalog và chứa các chức năng insert, update, delete
<?xml version="1.0" encoding="UTF-8"?>
<!
To change this license header, choose License Headers in Project Properties
To change this template file, choose Tools | Templates
and open the template in the editor
>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>List Catalog</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<h2>List Catalog</h2>
<f:view>
<h:form>
<h:dataTable var="catalog" value="#{catalogManagedBean.allCatalog}" border="1" cellpadding="2"
cellspacing="2">
<h:column>
<f:facet name="header">Catalog ID</f:facet>
<h:outputText value="#{catalog.catalogId}"/>
</h:column>
Trang 15IT Research Department @BKAP 2015 Page 15 / 18
<h:column>
<f:facet name="header">Catalog Name</f:facet>
<h:outputText value="#{catalog.catalogName}"/>
</h:column>
<h:column>
<f:facet name="header">Descriptions</f:facet>
<h:outputText value="#{catalog.description}"/>
</h:column>
<h:column>
<f:facet name="header">Edit</f:facet>
<h:commandLink action="updateCatalog" actionListener="#{catalogManagedBean.initUpdate()}"
value="Edit">
<f:param name="catalogId" value="#{catalog.catalogId}"/>
</h:commandLink>
</h:column>
<h:column>
<f:facet name="header">Delete</f:facet>
<h:commandLink action="listCatalog" actionListener="#{catalogManagedBean.deleteCatalog()}"
value="Delete">
<f:param name="catalogId" value="#{catalog.catalogId}"/>
</h:commandLink>
</h:column>
</h:dataTable>
<h:commandLink value="Insert Catalog" action="addCatalog"/>
</h:form>
</f:view>
</h:body>
</html>
addCatalog.xhtml: File xhtml thực hiện nhập dữ liệu catalog cần insert
<?xml version="1.0" encoding="UTF-8"?>
<!
To change this license header, choose License Headers in Project Properties
To change this template file, choose Tools | Templates
and open the template in the editor
>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert Catalog</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<h2>Insert Catalog</h2>
<f:view>
<h:form>
<h:panelGrid border="1" cellpadding="2" cellspacing="2" columns="3">
<h:outputLabel value="Catalog Name" for="catalogName"/>
<h:inputText id="catalogName" value="#{catalogManagedBean.catalogInsert.catalogName}"
required="true" requiredMessage="Catalog Name is required"/>
<h:message for="catalogName"/>
<h:outputLabel value="Description" for="description"/>
<h:inputText id="description" value="#{catalogManagedBean.catalogInsert.description}"/>
Trang 16To change this license header, choose License Headers in Project Properties
To change this template file, choose Tools | Templates
and open the template in the editor
>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert Catalog</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<h2>Insert Catalog</h2>
<f:view>
<h:form>
<h:panelGrid border="1" cellpadding="2" cellspacing="2" columns="3">
<h:outputLabel value="Catalog Name" for="catalogName"/>
<h:inputText id="catalogName" value="#{catalogManagedBean.catalogInsert.catalogName}"
required="true" requiredMessage="Catalog Name is required"/>
<h:message for="catalogName"/>
<h:outputLabel value="Description" for="description"/>
<h:inputText id="description" value="#{catalogManagedBean.catalogInsert.description}"/>
<h:message for="description"/>
<h:commandLink value="Insert" action="listCatalog"
actionListener="#{catalogManagedBean.insertCatalog()}"/>
</h:panelGrid>
</h:form>
</f:view>
</h:body>
</html>
Step 4: Build and Run ứng dụng