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

JSF – làm việc với cơ sở dữ liệu

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 (644.38 KB, 21 trang )

JSF – Làm việc với CƠ SỞ DỮ LIỆU
JSF – Làm việc với CƠ SỞ DỮ LIỆU
Trong bài này, chúng ta làm việc với JSF kết nối cơ sở dữ liệu sử dụng JDBC thể liệt kê 1 bảng dữ
liệu, thêm mẫu tin mới, cập nhật thông tin của dòng dữ liệu cũng như xóa 1 dòng dữ liệu. Giả sử
Database được thiết kế như sau:

Sau khi hoàn tất, ta có giao diện như sau:

Khi nhấn link “Insert New” sẽ cho ta trang thêm Lớp học mới

Khi nhấn Link Edit, sẽ load thông tin của dòng được chọn và cho hiệu chỉnh


Khi nhấn link Delete, sẽ xóa dòng được chọn.
Trong ví dụ này tôi dùng NetBeans IDE để thiết kế (Eclipse hay IDE khác cũng vậy)
Bước 1: Tạo 1 Web Application mới, chọn Framework là Java Server Faces như hình


Bước 2: Tạo Manage-bean

001 package vovanhai.wordpress.com;
002
003 import java.sql.Connection;
004 import java.sql.DriverManager;
005 import java.sql.PreparedStatement;
006 import java.sql.ResultSet;
007 import java.util.ArrayList;
008 import javax.faces.component.UIComponent;
009 import javax.faces.component.html.HtmlDataTable;
010 import javax.faces.event.ActionEvent;
011


012 /**
013 *
014 * @author VoVanHai
015 */
016 public class LophocBean {
017
018

private String msLop;

019

private String tenLop;


020

private String tenGVCN;

021
022

/** Creates a new instance of LophocBean */

023

public LophocBean() {
}

024

025
026

public LophocBean(String msLop, String tenLop, String tenGVCN)
{

027
028
029
030

this.msLop = msLop;
this.tenLop = tenLop;
this.tenGVCN = tenGVCN;
}

031
032

public String getMsLop() {

033
034

return msLop;
}

035
036
037

038

public void setMsLop(String msLop) {
this.msLop = msLop;
}

039
040

public String getTenGVCN() {

041
042

return tenGVCN;
}

043
044

public void setTenGVCN(String tenGVCN) {

045
046

}

this.tenGVCN = tenGVCN;

047

048

public String getTenLop() {

049
050

return tenLop;
}

051
052
053
054

public void setTenLop(String tenLop) {
this.tenLop = tenLop;
}

055
056

/**

057
058

* Liệt kê các record của bảng lớp học để hiển thị lên table
* @return


059

*/

060

public ArrayList<LophocBean> getAllLophoc() {

061

ArrayList<LophocBean> lst = new ArrayList<LophocBean>();

062

try {


06
3 iver");

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDr

Connection con =
06
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databas
4
eName=GC0563", "sa", "");
065

ResultSet rs =

con.createStatement().executeQuery("select * from Lophoc");

066

while (rs.next()) {

067

LophocBean lh = new LophocBean(
rs.getString(1),

068
069
070

rs.getString(2),
rs.getString(3));

071
072

lst.add(lh);
}

073

con.close();

074


} catch (Exception e) {

075
076

e.printStackTrace();
}

077
078
079

return lst;
}

080
081
082

/**
* Action dùng để insert 1 mẫu tin mới

083
084
085

* @return success nếu thành công
*/
public String InsertNew() {


086

try {

08
7 iver");

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDr

Connection con =
08
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databas
8
eName=GC0563", "sa", "");
089
090

String sql = "insert into lophoc values(?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);

091
092

ps.setString(1, msLop);
ps.setString(2, tenLop);

093

ps.setString(3, tenGVCN);


094

int x = ps.executeUpdate();

095

if (x > 0) {

096

return "success";

097

}

098

} catch (Exception e) {

099
100

e.printStackTrace();
}

101
102

return "failed";

}


103
104

/**

105
106

* Action delete dùng để xóa mẫu tin được chọn
* @param evt

107

*/

108

public void deleteAction(ActionEvent evt) {

109

// We get the table object
HtmlDataTable table = getParentDatatable((UIComponent)
110
evt.getSource());
111
112


// We get the object on the selected line.
Object o = table.getRowData();

113

LophocBean selLh = (LophocBean) o;

114

try {

11
5 iver");

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDr

Connection con =
11
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databas
6
eName=GC0563", "sa", "");
117
118

String sql = "delete lophoc where msLop=?";
PreparedStatement ps = con.prepareStatement(sql);

119
120


ps.setString(1, selLh.msLop);
ps.executeUpdate();

121

} catch (Exception e) {
e.printStackTrace();

122
123
124

}
}

125
126

/**

127
128

* Action dùng để chọn mẫu tin cần cập nhật
* @param evt

129

*/


130

public void editBook(ActionEvent evt) {

131

// We get the table object
HtmlDataTable table = getParentDatatable((UIComponent)
132
evt.getSource());
133
134

// We get the object on the selected line.
Object o = table.getRowData();

135
136

LophocBean lh = (LophocBean) o;
this.msLop = lh.msLop;

137
138

this.tenLop = lh.tenLop;
this.tenGVCN = lh.tenGVCN;

139


}

140
141

// Method to get the HtmlDataTable.

142

private HtmlDataTable getParentDatatable(UIComponent compo) {

143

if (compo == null) {

144

return null;


145

}

146

if (compo instanceof HtmlDataTable) {

147


return (HtmlDataTable) compo;

148

}

149
150

return getParentDatatable(compo.getParent());
}

151
152

/**

153
154

* Cập nhật dữ liệu được chọn lên cơ sở dữ liệu.
* @return

155

*/

156


public String update() {

15
try {
7
15
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDr
8 iver");
Connection con =
15
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databas
9
eName=GC0563", "sa", "");
16
String sql = "update lophoc set tenLop=?, tenGVCN=?
0 where msLop=?";
161
162

PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, tenLop);

163
164

ps.setString(2, tenGVCN);
ps.setString(3, msLop);

165


int x = ps.executeUpdate();

166

if (x > 0) {

167

return "success";

168

}

169
170

} catch (Exception e) {
e.printStackTrace();

171

}

172

return "failed";

173
174 }


}

Bước 3: Thiết kế giao diện
Tạo trang liệt kê danh sách các lớp học: Lophoc.jsp

01 <%@page contentType="text/html" pageEncoding="UTF-8"%>
02
03 <%@taglib prefix="f" uri=" />04 <%@taglib prefix="h" uri=" />05
06 " />07
08 <f:view>
09

<html>


10

<head>


12
<title>JSP Page</title>
11

13
14


</head>
<body>

15

DANH SÁCH LỚP HỌC



16

<h:form id="frm">

17


18

var="lh" id="table"

19
20

value="#{lophoc.allLophoc}"
>

21

<h:column id="ms" headerClass="headertext">

22


<f:facet name="header">

2
3 ã số Lớp"/>
2
4
25


3
0
31



3
6
3
7 />
3
8
39



</h:column>
<h:column id="actions" headerClass="headertext">

40

<f:facet name="header">


42
</f:facet>
41

4
3
4
4 Book}" action="edit"/> -

actionListener="#{lophoc.edit


4
5 "#{lophoc.deleteAction}"/>
4
</h:column>
6
47

48

<%--<f:facet name="footer">

49
50

<h:panelGroup style="align:right">


51
52

</h:panelGroup>
</f:facet>--%>

53
54
55
56

</h:dataTable>
</h:form>
</body>
</html>

57 </f:view>
Trang edit.jsp


01 <%@page contentType="text/html" pageEncoding="UTF-8"%>
02 <%@taglib prefix="f" uri=" />03 <%@taglib prefix="h" uri=" />04
05 " />06
07
08 <f:view>
09
10

<html>
<head>


12
<title>JSP Page</title>
11

13
14

</head>
<body>


16
<h:form>
15


17

<h:panelGrid columns="2">

18

<h:outputLabel for="ms" value="Mã số lớp"/>

1
9 nly="true"/>


20
21

<h:outputLabel for="ht" value="Tên lớp"/>

22

<h:inputText id="ht" value="#{lophoc.tenLop}"/>

23
24

<h:outputLabel for="gv" value="Tên GVCN"/>

25

<h:inputText id="gv" value="#{lophoc.tenGVCN}"/>



26

</h:panelGrid>

2
7 te}"/>
2
8

" />06
07
08 <f:view>

09
10

<html>
<head>


12
<title>JSP Page</title>
11

13
14
15

</head>
<body>



16

<h:form>

17

<h:panelGrid columns="2">

18


<h:outputLabel for="ms" value="Mã số lớp"/>

19

<h:inputText id="ms" value="#{lophoc.msLop}"/>

20

<h:outputLabel for="ht" value="Tên lớp"/>

21

<h:inputText id="ht" value="#{lophoc.tenLop}"/>

22

<h:outputLabel for="gv" value="Tên GVCN"/>

23

<h:inputText id="gv" value="#{lophoc.tenGVCN}"/>
</h:panelGrid>

24
2
5 rtNew}"/>
2
6
27

28

" />06
07
08 <f:view>
09
10

<html>
<head>


12
<title>JSP Page</title>
11


13
14

</head>
<body>

15

<h:outputText value="Error"/>


</body>

16

17
</html>
18 </f:view>
Bước 4: Cấu hình
Facees-config.xml ở dạng PageFlow

dạng XML

01 <?xml version='1.0' encoding='UTF-8'?>
02
03 xmlns=" />04
05
06

xmlns:xsi=" />xsi:schemaLocation=" />

07

/>

08

<managed-bean>

09

<managed-bean-name>lophoc</managed-bean-name>
class>vovanhai.wordpress.com.LophocBean</managed-bean-class>
11
12

<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

13

<navigation-rule>

14
15
16

</navigation-rule>
<navigation-rule>


17
18

<from-view-id>/Lophoc.jsp</from-view-id>
<navigation-case>

19
20

<from-outcome>insert</from-outcome>
<to-view-id>/insert.jsp</to-view-id>

21
22
23
24

</navigation-case>
<navigation-case>
<from-outcome>edit</from-outcome>
<to-view-id>/edit.jsp</to-view-id>

25
26

</navigation-case>
</navigation-rule>

27
28


<navigation-rule>
<from-view-id>/insert.jsp</from-view-id>

29
30

<navigation-case>
<from-outcome>success</from-outcome>

31
32

<to-view-id>/Lophoc.jsp</to-view-id>
</navigation-case>

33
34

<navigation-case>
<from-outcome>error</from-outcome>

35
36

<to-view-id>/error.jsp</to-view-id>
</navigation-case>

37
38

39
40
41
42
43
44
45
46
47
48

</navigation-rule>
<navigation-rule>
<from-view-id>/edit.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/Lophoc.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failed</from-outcome>
<to-view-id>/error.jsp</to-view-id>
</navigation-case>
</navigation-rule>

49 </faces-config>
Cấu trúc chương trình sau khi hoàn tất


Bước 5: Thực thi chương trình và thưởng thức
Chúc thành công!


Like
Be the first to like this.

22 Responses to “JSF – Làm việc với CƠ SỞ DỮ LIỆU”

1.

Sgboy17 said
May 4, 2011 at 2:22 am

Chào anh, e nghĩ mãi không ra cách sắp xếp để thêm phần search book. Vấn đề chính là
sau khi nhấn vào nút search, sẽ chuyển qua trang kết quả. Nhưng không thể truyền tham
số search về cho server để thực thi. (thuộc tính value của chưa nhận được giá trị với sql
query có where) .


2.

Đỉnh said
May 31, 2011 at 4:30 am

Dear thầy!
Thầy ơi cho em hỏi, khi em load trang viewAccount.jsp,nó báo là:
„#{RegisterBean1.getAllAccount}‟ Property „getAllAccount‟ not found on type
demo.RegisterBean1. ( cai getAllAccount cua em chinh la getAllLophoc cua thầy.)

3.

Đỉnh said

May 31, 2011 at 4:46 am

Cai allLophoc la cai nào vậy thầy? nếu là getAllLophoc thì nó là 1 hàm, sao nam trong
thuoc tinh value dc?

4.

Võ Văn Hải said
May 31, 2011 at 2:20 pm

Tữ động nó sẽ bỏ get, viết thường chữ đầu xuống. Đây là nguyên tắc cơ bản.

5.

Đỉnh said
June 1, 2011 at 1:56 am

Yeah! cam on thay, giờ thi em đã hiểu.

6.


Quangtrieu said
September 16, 2011 at 8:33 am

Hi Thay,
Thay cho em hoi chut ah, e lam chuong trinh nhu vi du cua Thay ma khong chay duoc,
Nguyen nhan la no khong mo duoc connec den DB
Chuoi connec cua em la:
Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);

Connection con =
DriverManager.getConnection(“jdbc:sqlserver:192.168.100.221;databaseName=qlsv”,
“sa”, “BacAdm1n”);
Kinh mong thay chi dum!

7.

Võ Văn Hải said
September 16, 2011 at 2:25 pm

Bạn chắc là có mở cổng 1433 không đấy? Nếu bạn dùng SQL Studio 2005, 2008 thì mặc
định TCP/IP port bị disable và bạn phải enable nó lên như sau:
Mở “SQL Server Configuration Manager” lên sau đó chọn server instance bên trái, double
mục TCP/IP bên phải, chọn enable=Yes, mở Tab “IP address” gõ port 1433 vào IPAll hoặc
vào tất cả IP.

8.

Trần Công Vương said
October 30, 2011 at 7:57 pm

Em chào thầy ạ.Thầy có thể ví dụ thêm về phần view được không ạ?Bên cạnh 2
commanlink EDIT va DELETE có thêm 1 commanlink la VIEW để khi ta click VIEW thì nó
sẽ qua form khác và trên form đó sẽ hiển thị lên tất cả thông tin của GiaoVienChuNhiem
đó được không ạ?
Mong thầy sẽ cho ví dụ sớm.Em cảm ơn thầy trước.

9.



Khoa said
November 4, 2011 at 5:07 am

javax.faces.el.EvaluationException: java.lang.NullPointerException
at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMe
thodExpressionAdapter.java:102)
at
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java
:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:291)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)

at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protoc
ol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at model.User.checkUser(User.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at


sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25
)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:191)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMe
thodExpressionAdapter.java:88)
… 20 more
Em chào thầy , mong này giúp em sửa lỗi này. Em làm giống vd của thầy.
public String checkUser(){
String sql =”SELECT * FROM users WHERE username=? AND password=?”;
try{
PreparedStatement prepare= getConnectPlane().prepareStatement(sql);
prepare.setString(1, name);
prepare.setString(2, password);
ResultSet rs = prepare.executeQuery();

while(rs.next()){
return “index”;
}
}catch(SQLException e){e.printStackTrace();}
return “login”;
}
public Connection getConnectPlane(){
Connection con=null;
try{
Class.forName(“com.mysql.jdbc.Driver”);
con
=DriverManager.getConnection(“jdbc:mysql://localhost:3306/phplogin”,”root”,”root”);
}catch(Exception e){e.printStackTrace();}
return con;
}

10.


JSF said
November 4, 2011 at 5:58 am

Em chào thầy, em đang làm JSF, để có thể làm được các ví dụ
em cần phải có những bộ thư viện nòa ạ. MOng thầy cung cấp cho em.
Em xin cảm ơn thầy.

11.

JSF said
November 4, 2011 at 6:01 am


a4j:ajax event=”keyup” render=”out”

12.

Khoa said
November 7, 2011 at 7:44 am

Em chào thầy.
Chúng ta có thẻ truyền tham số vào phần value=”#{lophoc.allLophoc}” dược không ạ.
Giả sử em chỉ muốn search các em lớp 6 or lớp 7 tùy vào mình
public ArrayList getAllLopHoc(int lop_may)
{
tim kiếm trong database WHERE lop=lop_may
}
. SAu khi searcg xong , em muốn trình bày tên của 4 em trên 1 hàng được không ạ.
Mong thầy giúp đỡ.
Em cảm ơn thầy

13.

Khoa said
November 7, 2011 at 9:22 am


Em chào thầy , thầy có thể cho em biết em cần những gói thư viện nào để có thể làm các
vd liên quan tới các tag Em muốn làm các vd giông trong trang này
/>Hiện tại em đang có thư viện JSF 2.1, JSTL1.1
Mong thầy giúp đỡ


14.

Võ Văn Hải said
November 10, 2011 at 1:36 pm

2 thư viện chuẩn của JSF là jsf-api-….jar và jsf-impl-…jar, cái thẻ là thẻ của richfaces, bạn
có thể tìm hiểu thêm ở bài này

15.

Võ Văn Hải said
November 10, 2011 at 1:54 pm

“Em chào thầy, em đang làm JSF, để có thể làm được các ví dụ
em cần phải có những bộ thư viện nòa ạ. MOng thầy cung cấp cho em.
Em xin cảm ơn thầy.”
Vui lòng tìm kỹ trong blog này sẽ có cau trả lời

16.

Võ Văn Hải said
November 10, 2011 at 1:56 pm

Nó báo lỗi: Caused by: java.lang.NullPointerException
at model.User.checkUser(User.java:85)
Em coi thử chỗ dòng 85 của file User đó có đảm bảo connection đã thể hiện chưa?


17.


Khoa said
December 7, 2011 at 9:41 am

Thầy có thể chỉ cho em cách ch n 1 trang jsf vào 1 trang khác được không.
Ví dụ em tạo ra 1 trang menu, sau đó em ch n trang này cho các trang khác.
Trong jsp em dùng jsp:include, còn trong jsf em không biết.
Mong thầy giúp đỡ. Em chúc thầy mạnh khỏe.

18.

Do Dung said
February 23, 2012 at 3:07 pm

anh cho em hoi, trong cai vi du nay cua khi ta xoa duoc roi nhung lam the nao de loading
lai du lieu o chinh cai trang do a

19.

Ken said
May 11, 2012 at 3:25 pm

chao thay! e thac mat la khi minh nhan nut delete thi lam seo biet truyen tham so id cho
no a. thay co the giai thich ro hon dc hk a. mong thay giup do!

20.

Ken said
May 11, 2012 at 3:34 pm


Neu mh truyen tham 1 tham so cho nhu the nay:
Thi ben Lophocbean mh lam seo de nhan tham so nay ha Thay? va lieu e viet nhu vay co
dung chua?…Kinh mong thay giup dum e!


21.

Minh Phúc said
August 8, 2012 at 4:06 am

Chào a, tôi có 2 trang. Trên trang 1 tôi hiển thị dữ liệu từ bean được thiết lập là
SessionScoped, từ trang 1 chuyển qua trang 2 để thực hiện thao tác dữ liệu. Nhưng sau
khi thay đổi dữ liệu thành công và database đã thay đổi nhưng khi quay về trang 1 dữ liệu
vẫn ko thay đổi. Nếu dùng ViewScoped thì ko thể chuyển dữ liệu qua trang 2 được hoặc a
có cách nào giúp chuyển dữ liệu qua trang 2 từ trang 1 ko (trang 2 và trang 1 dùng cùng
1 bean). A có cách nào giúp tôi giải quyết được vấn đề đó ko?

22.

Võ Văn Hải said
August 29, 2012 at 4:08 am

Chào a, tôi có 2 trang. Trên trang 1 tôi hiển thị dữ liệu từ bean được thiết lập là
SessionScoped, từ trang 1 chuyển qua trang 2 để thực hiện thao tác dữ liệu. Nhưng sau
khi thay đổi dữ liệu thành công và database đã thay đổi nhưng khi quay về trang 1 dữ liệu
vẫn ko thay đổi. Nếu dùng ViewScoped thì ko thể chuyển dữ liệu qua trang 2 được hoặc a
có cách nào giúp chuyển dữ liệu qua trang 2 từ trang 1 ko (trang 2 và trang 1 dùng cùng
1 bean). A có cách nào giúp tôi giải quyết được vấn đề đó ko?
Anh có thể send mail cho tôi demo của anh không? nói vầy thật khó trả lời.




×