Professional Documents
Culture Documents
Java Allinone Part 04 PDF
Java Allinone Part 04 PDF
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
1- Regular expression
ử dụng String.matches(String)
4- S
6- Nhóm (Group)
1- Regular expression
Một biểu thức chính quy (Regular expressions) định nghĩa một khuôn mẫu (pattern) tìm kiếm chuỗi.
Nó có thể được sử dụng tìm kiếm, sửa đổi, và thao tác trên văn bản. Khuôn mẫu được định nghĩa bởi
biểu thức chính quy có thể khớp một hoặc một vài lần, hoặc không khớp với một văn bản cho trước.
Biểu thức chính quy (Regular expression) được hỗ trợ bởi hầu hết các ngôn ngữ lập trình, ví dụ,
Java, C#, C/C++, v..v Thật không may mỗi ngôn ngữ hỗ trợ biểu thức thông thường hơi khác nhau.
2 ^regex Biểu thức chính quy phải khớp tại điểm bắt đầu
4 [abc] Thiết lập định nghĩa, có thể khớp với a hoặc b hoặc c.
5 [abc][vz] Thiết lập định nghĩa, có thể khớp với a hoặc b hoặc c theo sau là v hay z.
6 [^abc] Khi dấu ^ xuất hiện như là nhân vật đầu tiên trong dấu ngoặc vuông, nó phủ nhận
mô hình. Điều này có thể khớp với bất kỳ ký tự nào ngoại trừ a hoặc b hoặc c.
7 [a-d1-7] Phạm vi: phù hợp với một chuỗi giữa a và điểm d và con số từ 1 đến 7.
18 \b Ký tự thuộc a-z hoặc A-Z hoặc 0-9 hoặc _, viết ngắn gọn cho [a-zA-Z0-9_].
19 * Xuất hiện 0 hoặc nhiều lần, viết ngắn gọn cho {0,}
20 + Xuất hiện 1 hoặc nhiều lần, viết ngắn gọn cho {1,}
24 *? * có nghĩa là xuất hiện 0 hoặc nhiều lần, thêm ? phía sau nghĩa là tìm kiếm khớp
nhỏ nhất.
1
2 \.[{(*+?^$|
Những ký tự liệt kê ở trên là các ký tự đặc biệt. Trong Java Regex bạn muốn nó hiểu các ký tự đó
theo cách thông thường bạn cần thêm dấu \ ở phía trước.
Chẳng hạn ký tự chấm . java regex đang hiểu là một ký tự bất kỳ, nếu bạn muốn nó hiểu là một ký tự
chấm thông thường, cần phải có dấu \ phía trước.
1
2 // Mẫu regex mô tả một ký tự bất kỳ.
3
4 String regex = ".";
5
● Class String
1
2 ...
3
4
5
// Kiểm tra đối tượng toàn bộ String có khớp với regex hay không.
..
Sử dụng method String.matches(String regex) cho phép bạn kiểm tra toàn bộ String có khớp với
một regex hay không. Đây là một cách thông dụng nhất. Hãy xem các ví dụ:
StringMatches.java
?
1
2 package org.o7planning.tutorial.regex.stringmatches;
3
4
5
6
public class StringMatches {
7
8
9
10
11 public static void main(String[] args) {
12
13
14
15
16 String s1 = "a";
17
18 System.out.println("s1=" + s1);
19
20
// Kiểm tra toàn bộ s1
21
22
23 // Khớp với bất kỳ ký tự nào
24
25 // Quy tắc: .
26
27
// ==> true
28
29
30 boolean match = s1.matches(".");
31
32 System.out.println("-Match . " + match);
33
34
35
36
37 s1 = "abc";
38
39 System.out.println("s1=" + s1);
40
41
42
43 // Kiểm tra toàn bộ s1
44
45 // Khớp với bất kỳ ký tự nào.
46
47
// ==> false (Rõ ràng, chuỗi 3 ký tự sao khớp với 1 ký tự bất kỳ?)
48
49
50 match = s1.matches(".");
51
52 System.out.println("-Match . " + match);
53
54
55
56
57 // Kiểm tra toàn bộ s1
58
59 // Khớp với bất kỳ ký tự nào 0 hoặc nhiều lần
60
61
// Kết hợp các quy tắc: . và *
62
63
64 // ==> true
65
66 match = s1.matches(".*");
67
68
System.out.println("-Match .* " + match);
69
70
71
72
73 String s2 = "m";
74
75
System.out.println("s2=" + s2);
76
77
78 // Kiểm tra toàn bộ s2
79
80 // Bắt đầu bởi m
81
82
83
84 // Quy tắc ^
85
86 // true
87
88
match = s2.matches("^m");
89
90
91 System.out.println("-Match ^m " + match);
92
93
94
95
s2 = "mnp";
96
97
98 System.out.println("s2=" + s2);
99
10 // Kiểm tra toàn bộ s2
0
10
// Bắt đầu bởi m
1
10
2 // Quy tắc ^
10
3 // ==> false (Rõ ràng, chuỗi 3 ký tự sao khớp với 1 ký tự bất kỳ bắt đầu bởi m)
match = s2.matches("^m");
// Quy tắc ^ và . và +
// true
match = s2.matches("^m.+");
String s3 = "p";
System.out.println("s3=" + s3);
// Quy tắc $
// true
match = s3.matches("p$");
s3 = "2nnp";
System.out.println("s3=" + s3);
// ==> false (Rõ ràng, chuỗi 4 ký tự sao khớp với 1 ký tự p cuối cùng)
match = s3.matches("p$");
// true
match = s3.matches(".n{1,3}p$");
String s4 = "2ybcd";
System.out.println("s4=" + s4);
// Bắt đầu là 2
// true
match = s4.matches("2[xyz].+");
String s5 = "2bkbv";
// true
match = s5.matches(".+[abc][zv].*");
}
}
SplitWithRegex.java
?
1
2 package org.o7planning.tutorial.regex.stringmatches;
3
4
5
6
public class SplitWithRegex {
7
8
9
10
11 public static final String TEXT = "This is my text";
12
13
14
15
16 public static void main(String[] args) {
17
18 System.out.println("TEXT=" + TEXT);
19
20
// Khoảng trắng xuất hiện 1 hoặc nhiều lần.
21
22
23 // Các ký tự khoảng trắng: \t\n\x0b\r\f
24
25 // Kết hợp quy tắc: \s và +
// 4
System.out.println(splitString.length);
EitherOrCheck.java
?
1
2 package org.o7planning.tutorial.regex.stringmatches;
3
4
5
6
public class EitherOrCheck {
7
8
9
10
11 public static void main(String[] args) {
12
13
14
15
16 String s = "The film Tom and Jerry!";
17
18 // Kiểm tra toàn bộ s
19
20
// Bắt đầu bởi ký tự bất kỳ xuất hiện 0 hoặc nhiều lần
21
22
23 // Tiếp theo là từ Tom hoặc Jerry
24
25 // Kết thúc bởi ký tự bất kỳ xuất hiện 0 hoặc nhiều lần
26
27
// Kết hợp các quy tắc: ., *, X|Z
28
29
30 // true
31
boolean match = s.matches(".*(Tom|Jerry).*");
System.out.println("s=" + s);
// false
match = s.matches(".*(Tom|Jerry).*");
System.out.println("s=" + s);
// true
match = s.matches(".*(Tom|Jerry).*");
System.out.println("s=" + s);
2. Matcher là một phương tiện để so khớp chuỗi dữ liệu đầu vào với đối tượng Pattern đã được tạo
ra ở trên. Class này không có cấu tử public, và chúng ta lấy đối tượng này thông qua method
matcher(String) của đối tượng Pattern. Với tham số đầu vào String là văn bản cần kiểm tra.
3. PatternSyntaxException sẽ bị ném ra nếu biểu thức chính quy có ngữ pháp không chính xác.
1
2 String regex= ".xx.";
3
4 // Tạo đối tượng Pattern thông qua method tĩnh.
5
6
Pattern pattern = Pattern.compile(regex);
7
8
9 // Lấy ra đối tượng Matcher
1
2 public static Pattern compile(String regex, int flags) ;
3
4
5
6
public static Pattern compile(String regex);
7
?
1
2 public int start()
3
4
5
6
public int start(int group)
7
8
9
10
11 public int end()
12
13
14
15
16 public int end(int group)
17
18
19
20
public String group()
21
Đây là một ví dụ sử dụng Matcher và method find() để tìm kiếm các chuỗi con khớp với một biểu
thức chính quy.
MatcherFind.java
?
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class MatcherFind {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 final String TEXT = "This \t is a \t\t\t String";
24
25
26
27
// Khoảng trắng xuất hiện 1 hoặc nhiều lần.
28
while (matcher.find()) {
i++;
Method Matcher.lookingAt()
MatcherLookingAt.java
?
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class MatcherLookingAt {
14
15
16
17
18 public static void main(String[] args) {
19
20
String country1 = "iran";
21
22
23 String country2 = "Iraq";
24
25
26
27
// Bắt đầu bởi I tiếp theo là ký tự bất kỳ.
28
29
30 // Tiếp theo là ký tự a hoặc e.
31
String regex = "^I.[ae]";
matcher.reset(country2);
6- Nhóm (Group)
Một biểu thức chính quy bạn có thể tách ra thành các nhóm (group):
?
1
2 // Một biểu thức chính quy
3
4 String regex = "\\s+=\\d+";
5
6
7
8
// Viết dưới dạng group, bởi dấu ()
Các group có thể lồng nhau, và như vậy cần một quy tắc đánh chỉ số các group. Toàn bộ pattern
được định nghĩa là group số 0. Còn lại được mô tả giống hình minh họa dưới đây:
Chú ý: Sử dụng (?:pattern) để thông báo với Java không xem đây là một group (None-capturing
group)
Từ Java 7, bạn có thể xác định một group có tên (?<name>pattern), Và bạn có thể truy cập các nội
dung khớp với Matcher.group(String name). Điều này làm Regex dài hơn, nhưng mã này là có ý
nghĩa hơn, dễ hơn.
Nhóm bắt theo tên cũng có thể được truy cập thông qua Matcher.group(int group) với cách đánh chỉ
số tương tự.
Nội bộ, Java chỉ lập bản đồ (ánh xạ) từ tên đến chỉ số nhóm. Do đó, bạn không thể sử dụng cùng tên
để bắt 2 nhóm khác nhau.
Hãy xem một ví dụ sử dụng đánh tên cho nhóm (group) ( Java >=7)
NamedGroup.java
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class NamedGroup {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23
24
25 final String TEXT = " int a = 100;float b= 130;float c= 110 ; ";
26
27
28
29
30 // Sử dụng (?<groupName>pattern) để định nghĩa một Group có tên: groupName
// Định nghĩa group có tên declare: sử dụng (?<declare> ...)
while (matcher.find()) {
System.out.println(group);
System.out.println("------------------------------");
?
1
2 // Đây là một regex
3
4 // Bắt gặp ký tự bất kỳ 0 hoặc nhiều lần,
5
6
// sau đó tới ký tự ' và tiếp theo là >
7
8
9 String regex = ".*'>";
10
*? sẽ tìm ra một phù hợp nhỏ nhất. Chúng ta xem ví dụ sau:
NamedGroup2.java
?
1
2 package org.o7planning.tutorial.regex;
3
4
5
6
import java.util.regex.Matcher;
7
8
9 import java.util.regex.Pattern;
10
11
12
13
public class NamedGroup2 {
14
15
16
17
18 public static void main(String[] args) {
19
20
String TEXT = "<a href='http://HOST/file/FILE1'>File 1</a>"
21
22
23 + "<a href='http://HOST/file/FILE2'>File 2</a>";
24
25
// Java >= 7.
while (matcher.find()) {
Java cơ bản
Mục lục
3- Runnable Interface
Java cơ bản
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
3- Runnable Interface
ử dụng yield()
7- S
● HelloMain là một class thông thường có hàm main, nó là một luồng chính (main thread).
● HelloThread là một class mở rộng từ class Thread. Nó được tạo và chạy kích hoạt chạy bên
trong luồng chính và sẽ chạy song song với luồng chính.
?
1
2 package org.o7planning.tutorial.thread.hellothread;
3
4
5
6 public class HelloMain {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
int idx = 1;
15
16
17
18
19 for (int i = 0; i < 2; i++) {
20
21
22
23 System.out.println("Main thread running " + idx++);
24
25 // Ngủ 2101 milli giây.
26
27 Thread.sleep(2101);
28
29 }
// Chạy thread
helloThread.start();
for (int i = 0; i < 3; i++) {
Thread.sleep(2101);
}
HelloThread.java
?
1
2 package org.o7planning.tutorial.thread.hellothread;
3
4
5
6 public class HelloThread extends Thread {
7
8
9
10 // Code trong hàm run() sẽ được thực thi khi
11
12 // thread được chạy (start)
13
14
@Override
15
16
public void run() {
17
18
19 int index = 1;
20
21
22
23 for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1030);
} catch (InterruptedException e) {
}
}
}
Kết quả chạy class HelloMain:
3- Runnable Interface
Bạn cũng có thể tạo một thread t ừ một class thi hành interface Runnable. Xem ví dụ minh họa:
RunnableDemo.java
?
1
2 package org.o7planning.tutorial.thread.runnable;
3
4
5
6 public class RunnableDemo implements Runnable {
7
8
9
10 @Override
11
12 public void run() {
13
14
int idx = 1;
15
16
for (int i = 0; i < 5; i++) {
17
18
System.out.println("Hello from RunnableDemo " + idx++);
// Ngủ 2 giây.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
RunnableTest.java
?
1
2 package org.o7planning.tutorial.thread.runnable;
3
4
5
6 public class RunnableTest {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
System.out.println("Main thread running..");
15
16
17
18
// Tạo một thread từ Runnable.
thread.start();
// Ngủ 5 giây.
Thread.sleep(5000);
}
Chạy class RunnableTest:
4- Luồng Deamon (Deamon Thread)
Java chia thread làm 2 loại một loại thông thường và Deamon Thread. Chúng chỉ khác nhau ở cách
thức ngừng hoạt động. Trong một chương trình các luồng thông thường và luồng Deamon chạy song
song với nhau. Khi tất cả các luồng thông thường kết thúc, mọi luồng Deamon cũng sẽ bị kết thúc
theo bất kể nó đang làm việc gì.
Chú ý:
Sử dụng s etDeamon(boolean) để sét đặt một luồng là Deamon hoặc không. Chú ý, bạn chỉ có thể
etDeamon(boolean) khi thread chưa được chạy. Điều đó có nghĩa là khi thread đã chạy
gọi hàm s
bạn không thể chuyển luồng từ non-deamon sang d
eamon và ngược lại.
Khi một luồng mới được tạo ra, nó được thừa hưởng đặc tính deamon từ luồng cha. Như vậy khi
ain của 1 class nó vốn là luồng n
bạn tạo một luồng trong hàm m on-deamon, vì vậy thread tạo ra
mặc định cũng là none-deamon. Như vậy nếu bạn tạo một luồng mới trong một luồng Deamon,
mặc định nó cũng sẽ là Deamon.
1
2 Thread thread = new MyThread();
3
4
5
6 // sét luồng này là deamon.
7
8 // Chỉ gọi được method này khi thread chưa start.
9
10
11
// Trong trường hợp start rồi sẽ bị một ngoại lệ.
thread.setDeamon(true);
thread.setDeamon(false);
Để dễ hiểu chúng ta xem ví dụ sau, chúng ta cần 3 class tham gia vào minh họa:
NoneDeamonThread.java
?
1
2 package org.o7planning.tutorial.thread.deamon;
3
4
5
6 public class NoneDeamonThread extends Thread {
7
8
9
10 @Override
11
12 public void run() {
13
14
int i = 0;
15
16
17
18
19 // Vòng lặp 10 lần. Luồng này sẽ kết thúc.
20
21 while (i < 10) {
22
System.out.println(" - Hello from None Deamon Thread " + i++);
try {
// Ngủ 1 giây.
Thread.sleep(1000);
} catch (InterruptedException e) {
}
DeamonThread.java
1
2 package org.o7planning.tutorial.thread.deamon;
3
4
5
6 class DeamonThread extends Thread {
7
8
9
10 @Override
11
12 public void run() {
13
14
int count = 0;
15
16
17
18
19 // Vòng lặp vô tận.
while (true) {
try {
// Ngủ 2 giây.
sleep(2000);
} catch (InterruptedException e) {
}
}
DaemonTest.java
1
2 package org.o7planning.tutorial.thread.deamon;
3
4
5
6 public class DaemonTest {
7
8
9
10 public static void main(String[] args) {
11
12 System.out.println("==> Main Thread running..\n");
13
14
// Tạo một Thread
15
16
Thread deamonThread = new DeamonThread();
17
18
19 // Sét nó là Deamon Thread.
20
21 deamonThread.setDaemon(true);
22
23 deamonThread.start();
24
25
26
// Tạo một Thread khác
new NoneDeamonThread().start();
try {
// Ngủ 5 giây.
Thread.sleep(5000);
} catch (InterruptedException e) {
}
Kết quả chạy class DeamonTest:
Hình minh họa trên cho thấy rằng luồng Deamon đã bị dừng lại khi tất cả các luồng thông thường đã
dừng. Mặc dù code của nó là chạy vô tận.
1
2 // Thread cha cần phải đợi cho tới khi luồng này kết thúc
3
4 // mới được chạy tiếp.
5
6 // (Nó tương đương với gọi join(0) )
7
8 public final void join() throws InterruptedException;
9
10
11
12 // Thread cha cần phải đợi 'millis' milli giây mới được tiếp tục chạy.
13
14
15 // kể từ lúc gọi join(long).
16
// Nếu tham số millis = 0 nghĩa là đợi cho tới khi luồng này kết thúc.
// Thread cha cần phải đợi 'millis' milli giây và 'nanos' nano giây mới được tiếp tục
chạy.
// Nếu tham số millis = 0 & nanos = 0 nghĩa là đợi cho tới khi luồng này kết thúc.
public final synchronized void join(long millis, int nanos) throws InterruptedException;
Hãy xem một ví dụ minh họa:
JoinThread.java
?
1
2 package org.o7planning.tutorial.thread.join;
3
4
5
6 public class JoinThread extends Thread {
7
8 private String threadName;
9
10 private int count;
11
12
13
14
public JoinThread(String threadName, int count) {
15
16
this.threadName = threadName;
17
18
19 this.count = count;
20
21 }
22
23
24
@Override
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
JoinTest.java
1
2 package org.o7planning.tutorial.thread.join;
3
4
5
6 public class JoinTest {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
System.out.println("\n==> Main thread starting..\n");
15
16
17
18
19 Thread joinThreadA = new JoinThread("A*", 2);
20
21 Thread joinThreadB = new JoinThread("B*", 3);
22
23
24
25 // Thread thông thường, sẽ không sử dụng join().
26
27 Thread noJoinThreadC = new JoinThread("C", 5);
28
29
30
31
32 joinThreadA.start();
joinThreadB.start();
noJoinThreadC.start();
// Sử dụng join()
joinThreadA.join();
joinThreadB.join();
}
Kết quả chạy class JoinTest:
Ví dụ sử dụng join(long millis):
JoinTest2.java
?
1
2 package org.o7planning.tutorial.thread.join;
3
4
5
6 public class JoinTest2 {
7
8
9
10 public static void main(String[] args) throws InterruptedException {
11
12
13
14
System.out.println("\n==> Main thread starting..\n");
15
16
17
18
19 Thread joinThreadA = new JoinThread("A*", 5);
20
21
22
23 joinThreadA.start();
24
// Luồng cha (main) phải chờ 5000 milli giây
// mới được tiếp tục chạy. (Không nhất thiết phải A kết thúc)
joinThreadA.join(5000);
}
Kết quả chạy ví dụ:
ThreadExceptionDemo.java
?
1
2 package org.o7planning.tutorial.thread.exception;
3
4
5
6 import java.util.Random;
7
8
9
10 public class ThreadExceptionDemo {
11
12
13
14
public static class RunnableTest implements Runnable {
15
16
17
18
19 @Override
20
21 public void run() {
22
23 System.out.println("Thread running ..");
24
25
26
27 while (true) {
28
29 Random r = new Random();
30
31
// Một số ngẫu nhiên từ 0 - 99
32
33
int i = r.nextInt(100);
34
35
36 System.out.println("Next value " + i);
37
38
39
40 try {
41
42
43 Thread.sleep(2000);
44
45 } catch (InterruptedException e) {
46
47 }
48
49
50
if (i > 70) {
Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler() {
@Override
});
thread.start();
}
Kết quả chạy ví dụ:
7- Sử dụng yield()
Về mặt lý thuyết, "yield" có nghĩa là để cho đi, từ bỏ, đầu hàng. Một luồng yield nói với máy ảo là nó
sẵn sàng để cho các thread khác được sắp xếp ở vị trí của nó. Điều này cho thấy rằng nó không phải
làm một cái gì đó quá quan trọng. Lưu ý rằng nó chỉ là một gợi ý, mặc dù, và không đảm bảo có hiệu
lực ở tất cả.
1
public static native void yield();
Như vậy phương thức yield() được sử dụng khi bạn bạn thấy rằng thread đó đang rảnh rỗi, nó không
phải làm việc gì quan trọng, nên nó gợi ý hệ điều hành tạm thời nhường quyền ưu tiên cho các luồng
khác.
Ví dụ dưới đây, có 2 luồng, mỗi luồng in ra một dòng văn bản 100K lần (con số đủ lớn để thấy sự
khác biệt). Một luồng được sét độ ưu tiên cao nhất và một luồng được sét độ ưu tiên ít nhất. Đo
khoảng thời gian kết thúc của 2 luồng.
YieldThreadExample.java
?
1
2 package org.o7planning.tutorial.thread.yield;
3
4
5
6 import java.util.Date;
7
8
9
10 public class YieldThreadExample {
11
12
13
14
private static Date importantEndTime;
15
16
private static Date unImportantEndTime;
17
18
19
20
21 public static void main(String[] args) {
22
23 importantEndTime = new Date();
24
25 unImportantEndTime = new Date();
26
27
28
29 System.out.println("Create thread 1");
30
31
32
33
Thread importantThread = new ImportantThread();
34
35
36
37
38 // Sét đặt độ ưu tiên cao nhất cho thread này.
39
40 importantThread.setPriority(Thread.MAX_PRIORITY);
41
42
43
44
45 System.out.println("Create thread 2");
46
47
48
49 Thread unImportantThread = new UnImportantThread();
50
51
52
53 // Sét đặt độ ưu tiên thấp nhất cho thread này.
54
55
unImportantThread.setPriority(Thread.MIN_PRIORITY);
56
57
58
59
60 // Start threads.
61
62 unImportantThread.start();
63
64 importantThread.start();
65
66
67
68 }
69
70
71
72
// Một nhiệm vụ quan trọng, yêu cầu độ ưu tiên cao.
73
74
static class ImportantThread extends Thread {
@Override
Thread.yield();
printTime();
@Override
printTime();
}
Kết quả: thread có ưu tiên thấp hơn đã hoàn thành công việc trước 51 mili giây so với thread có ưu
tiên cao hơn.
8- So sánh sleep() và wait()
TODO.
Java cơ bản
Mục lục
1- Giới thiệu
ách sử dụng
3.1- C
Java cơ bản
Thư viện điều khiển các loại cơ sở dữ liệu khác nhau trong Java
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
iới thiệu
1- G
1- Giới thiệu
Tài liệu này hướng dẫn các bạn download thư viện điều khiển một loại cơ sở dữ liệu nào đó, hiện tại
tôi hướng dẫn trên các loại database:
1. Oracle
2. MySQL
3. SQL Server.
● ojdbc14.jar: được biên dịch và đóng gói bởi Java phiên bản 1.4
● ojdbc6.jar: được biên dịch và đóng gói bởi Java phiên bản 6.
Chi tiết hơn bạn có thể xem và download tại website của Oracle:
● http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html
Bạn có thể download file ojdbc6.jar, nó có thể điều khiển cho database Oracle các phiên bản khác
nhau (XE, 10g, 11g, 12). Mà hầu hết các ứng dụng Java thời điểm này đều sử dụng Java phiên bản 6
hoặc mới hơn.
òi hỏi bạn phải có tài khoản Oracle (Đăng ký miễn phí).
Việc download tại website của Oracle đ
Trong trường hợp muốn nhanh chóng bạn có thể download theo đường link dưới đây:
● https://code.google.com/p/afirs/downloads/detail?name=ojdbc6.jar
1
2 <repositories>
3
4
<!-- Repository for ORACLE ojdbc6. -->
5
6
7 <repository>
8
9
<id>codelds</id>
10
11
12 <url>https://code.lds.org/nexus/content/groups/main-repo</url>
13
14
</repository>
15
16
17 </repositories>
18
19
20
21
22 .......
23
24
<dependencies>
......
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
.......
</dependencies>
1
2 // Driver class:
3
4
oracle.jdbc.driver.OracleDriver
5
6
7
8
9
// URL Connection String: (SID)
10
11
12 String urlString ="jdbc:oracle:thin:@myhost:1521:mysid"
// Or:
OracleConnUtils.java
?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class OracleConnUtils {
13
14
15
16
17 public static Connection getOracleConnection()
18
19
20 throws ClassNotFoundException, SQLException {
21
22 String hostName = "localhost";
23
24
25 String sid = "db11g";
26
27 String userName = "learningsql";
28
29
30 String password = "1234";
31
32
33
34
35 return getOracleConnection(hostName, sid, userName, password);
}
public static Connection getOracleConnection(String hostName, String sid,
SQLException {
// Nếu bạn dùng Java > 6, thì ko cần dòng này cũng được.
Class.forName("oracle.jdbc.driver.OracleDriver");
// Ví dụ: jdbc:oracle:thin:@localhost:1521:db11g
password);
return conn;
● http://mvnrepository.com/artifact/mysql/mysql-connector-java
Kết quả download được:
1
2 // Driver class:
3
4
com.mysql.jdbc.Driver
5
6
7
8
9
// URL Connection String:
// Ví dụ:
MySQLConnUtils.java
?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class MySQLConnUtils {
13
14
15
16
17 public static Connection getMySQLConnection()
18
19
20 throws ClassNotFoundException, SQLException {
21
22 String hostName = "localhost";
23
24
25 String dbName = "learningsql";
26
27 String userName = "root";
28
29
30 String password = "12345";
31
32
return getMySQLConnection(hostName, dbName, userName, password);
33
}
public static Connection getMySQLConnection(String hostName, String dbName,
ClassNotFoundException {
// Nếu bạn dùng Java > 5, thì ko cần dòng này cũng được.
Class.forName("com.mysql.jdbc.Driver");
// Ví dụ: jdbc:mysql://localhost:3306/simplehr
password);
return conn;
}
Trong một số trường hợp kết nối vào MySQL từ Java hoặc đơn giản là từ máy khác bị lỗi, nguyên
nhân có thể bạn chưa cấu hình MySQL server cho phép kết nối từ máy khác.
Bạn có thể xem lại mục cấu hình trong tài liệu " Hướng dẫn cài đặt và cấu hình MySQL
Community":
jTDS: là một mã nguồn mở thuần Java 100% (type 4) JDBC 3.0 điều khiển cho Microsoft SQL
Server (6,5, 7, 2000, 2005, 2008, 2012) và Sybase ASE (10, 11, 12, 15). jTDS dựa trên FreeTDS và
hiện là trình điều khiển JDBC nhanh nhất cho SQL Server và Sybase. jTDS là 100% tương thích với
JDBC 3.0, hỗ trợ forward-only và scrollable/updateable ResultSet v à thực hiện tất cả các phương
thức của DatabaseMetaData v à ResultSetMetaData.
● http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds
Kết quả download được:
4.1- Cách sử dụng (jtds)
1
2 // Driver Class
3
4
net.sourceforge.jtds.jdbc.Driver
5
6
7
8
9
// Connection URL String:
10
11
12 jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
13
14
15
// Example 1:
String url =
"jdbc:jtds:sqlserver://MYPC:1433/simplehr;instance=SQLEXPRESS;user=sa;passwor
d=s3cr3t";
getConnection(url);
// Example 2:
Ví dụ sử dụng JDBC kết nối vào Database SQLServer sử dụng thư viện JTDS.
SQLServerConnUtils_JTDS.java
?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class SQLServerConnUtils_JTDS {
13
14
15
16
17 // Kết nối vào SQLServer.
18
19
20 // (Sử dụng thư viện điều khiển JTDS)
21
22 public static Connection getSQLServerConnection_JTDS() throws SQLException,
23
24
25 ClassNotFoundException {
26
27 String hostName = "localhost";
28
29
30 String sqlInstanceName = "SQLEXPRESS";
31
32
String database = "simplehr";
33
34
35 String userName = "sa";
36
37
String password = "12345";
38
39
40
41
42
43 return getSQLServerConnection_JTDS(hostName, sqlInstanceName, database,
44
userName, password);
// Nếu bạn dùng Java > 5, thì ko cần dòng này cũng được.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
// Cấu trúc URL Connection dành cho SQLServer
// Ví dụ:
// jdbc:jtds:sqlserver://localhost:1433/simplehr;instance=SQLEXPRESS
password);
return conn;
Trong một số tình huống kết nối vào SQLServer và bị lỗi:
?
1
2 Exception in thread "main" java.sql.SQLException: Server tran-vmware has no
3 instance named SQLEXPRESS.
4
5
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:301)
6
7
8 at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
9
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at
org.o7planning.tutorial.jdbc.ConnectionUtils.getSQLServerConnection_JTDS(Connecti
onUtils.java:189)
at
org.o7planning.tutorial.jdbc.ConnectionUtils.getSQLServerConnection_JTDS(Connecti
onUtils.java:72)
at
org.o7planning.tutorial.jdbc.ConnectionUtils.getMyConnection(ConnectionUtils.java:31)
at org.o7planning.tutorial.jdbc.TestConnection.main(TestConnection.java:20)
Lỗi trên có thể do bạn chưa bật dịch vụ TCP/IP của SQLServer. Bạn có thể tham khảo thêm mục cấu
hình trong tài liệu: "Hướng dẫn cài đặt và cấu hình SQLServer Express ..." tại:
● Hướng dẫn cài đặt và cấu hình SQL Server Express 2014
Download:
● http://www.microsoft.com/en-us/download/details.aspx?id=11774
Giải nén file vừa download được.
Kết quả có được thư viện:
?
1
2 // Driver Class:
3
4
com.microsoft.sqlserver.jdbc.SQLServerDriver
5
6
7
8
9
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
10
11
12
13
14
// Url String:
15
String url =
"jdbc:sqlserver://ServerIp;Instance=SQLEXPRESS;databaseName=simplehr";
// Hoặc
String url =
"jdbc:sqlserver://ServerIp:1433;Instance=SQLEXPRESS;databaseName=simplehr";
SQLServerConnUtils_SQLJDBC.java
?
1
2 import java.sql.Connection;
3
4
import java.sql.DriverManager;
5
6
7 import java.sql.SQLException;
8
9
10
11
12 public class SQLServerConnUtils_SQLJDBC {
13
14
15
16
17 // Kết nối vào SQLServer.
18
19
20 // (Sử dụng thư viện điều khiển SQLJDBC)
21
22 public static Connection getSQLServerConnection_SQLJDBC()
23
24
25 throws ClassNotFoundException, SQLException {
26
27 String hostName = "localhost";
28
29
30 String sqlInstanceName = "SQLEXPRESS";
31
32
String database = "learningsql";
33
34
35 String userName = "sa";
36
37
String password = "12345";
38
39
40
41
42
43 return getSQLServerConnection_SQLJDBC(hostName, sqlInstanceName,
44
45
database, userName, password);
// Nếu bạn dùng Java > 5, thì ko cần dòng này cũng được.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Cấu trúc URL Connection dành cho SQLServer
// Ví dụ:
// jdbc:sqlserver://ServerIp:1433/SQLEXPRESS;databaseName=simplehr
password);
return conn;
Trong một số tình huống kết nối vào SQLServer và bị lỗi:
?
1
2 com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host
3 localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the
4 connection properties. Make sure that an instance of SQL Server is running on the host
5 and accepting TCP/IP connections at the port. Make sure that TCP connections to the
6 port are not blocked by a firewall.".
7
8
at
9
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerExc
1
eption.java:190)
0
1
1 at
1 com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServ
2 erException(SQLServerException.java:241)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnectio
n.java:1309)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:99
1)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:
827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
...
Lỗi trên có thể do bạn chưa Enable dịch vụ TCP/IP của SQLServer. Bạn có thể tham khảo thêm mục
cấu hình SQLServer trong tài liệu "Hướng dẫn cài đặt và cấu hình SQLServer Express ..." tại:
● Hướng dẫn cài đặt và cấu hình SQL Server Express 2014
1
2 Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The
3 TCP/IP connection to the host tran-vmware, port 1433 has failed. Error: "Connection
4 refused: connect. Verify the connection properties. Make sure that an instance of SQL
5 Server is running on the host and accepting TCP/IP connections at the port. Make sure
6 that TCP connections to the port are not blocked by a firewall.".
7
8
at
9
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerExc
1
eption.java:190)
0
1
1 at
1 com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServ
2 erException(SQLServerException.java:241)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnectio
n.java:1309)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:99
1)
at
com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:
827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
...
Đây là một lỗi khó chịu, vì khi chuyển sang sử dụng thư viện JTDS không bị lỗi này.
● TODO
● You should use JTDS
● https://github.com/mongodb/mongo-java-driver/downloads
Bạn cũng có thể download tại Maven Repository:
● http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
Xem thêm các chuyên mục:
Java cơ bản
Mục lục
2- JDBC là gì?
3- Java kết nối với database dựa trên nguyên tắc nào?
6- Connection
10- PreparedStatement
11- CallableStatement
Java cơ bản
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
atabase sử dụng trong tài liệu này
1- D
2- JDBC là gì?
3- J ava kết nối với database dựa trên nguyên tắc nào?
6- Connection
ác kiểu ResultSet
8- C
í dụ Insert dữ liệu
9- V
10- PreparedStatement
11- CallableStatement
● Cơ sở dữ liệu mẫu
2- JDBC là gì?
JDBC (Java Database Connectivity) là một API tiêu chuẩn dùng để tương tác với các loại cơ sở dữ
liệu quan hệ. JDBC có một tập hợp các class và các Interface dùng cho ứng dụng Java có thể nói
chuyện với các cơ sở dữ liệu.
1. DriverManager:
○ Là một class, nó dùng để quản lý danh sách các Driver (database drivers).
2. Driver:
○ Là một Interface, nó dùng để liên kết các liên lạc với cơ sở dữ liệu, điều khiển các liên
lạc với database. Một khi Driver được tải lên, lập trình viên không cần phải gọi nó một
cách cụ thể.
3. Connection :
○ Là một Interface với tất cả các method cho việc liên lạc với database. Nó mô tả nội dung
liên lạc. tất cả các thông tin liên lạc với cơ sở dữ liệu là thông qua chỉ có đối tượng
Connection.
4. Statement :
○ Là một Interface, gói gọn một câu lệnh SQL gửi tới cơ sở dữ liệu được phân tích, tổng
hợp, lập kế hoạch và thực hiện.
5. ResultSet:
○ ResultSet đại diện cho tập hợp các bản ghi lấy do thực hiện truy vấn.
3- Java kết nối với database dựa trên nguyên tắc nào?
Java sử dụng JDBC để làm việc với các cơ sở dữ liệu.
Ví dụ bạn làm việc với cơ sở dữ liệu Oracle từ Java bạn cần phải có Driver (Đó là class điều khiển
việc kết nối với loại cơ sở dữ liệu bạn muốn). Trong JDBC API chúng ta có java.sql.Driver, nó chỉ là
một interface, và nó có sẵn trong JDK. Như vậy bạn phải download thư viện Driver ứ ng với loại
Database mà bạn mong muốn.
● Chẳng hạn với Oracle thì class thi hành Interface java.sql.Driver đó là:
oracle.jdbc.driver.OracleDriver
java.sql.DriverManager là một class trong JDBC API. Nó làm nhiệm vụ quản lý các Driver.
● Cách 1: Bạn hãy cung cấp thư viện Driver điều khiển loại cơ sở dữ liệu đó, đây là cách trực
tiếp. Nếu bạn dùng DB oracle (hoặc DB khác) bạn phải download thư viện dành cho loại DB
này.
● Cách 2: Khai báo một "ODBC DataSource", và sử dụng cầu nối JDBC-ODBC để kết nối với
"ODBC DataSource" kia. Cầu nối JDBC-ODBC là thứ có sẵn trong JDBC API.
ODBC DataSource: Trên hệ điều hành Window bạn có thể khai báo một kết nối ODBC tới một loại
DB nào đó. Và như vậy chúng ta có một nguồn dữ liệu (Data Source).
Trong JDBC API, đã xây dựng sẵn một cầu nối JDBC-ODBC để JDBC có thể nói chuyện được với
ODBC Data Source.
Về tốc độ, cách 1 sẽ nhanh hơn cách 2, vì cách 2 phải sử dụng tới cầu nối.
● Oracle
● MySQL
● SQLServer
● ....
● Thư viện điều khiển các loại cơ sở dữ liệu khác nhau trong Java
Tạo thư mục libs trên project và copy các thư viện kết nối trực tiếp các loại database Oracle, MySQL,
SQLServer mà bạn vừa download được ở trên vào. Bạn có thể copy hết hoặc một trong các thư viện
đó, theo loại DB mà bạn sử dụng.
Chú ý: Bạn chỉ cần download một Driver ứng với loại Database mà bạn quen thuộc. Cơ sở dữ liệu
dùng làm ví dụ trong tài liệu này bạn có thể lấy tại:
● Cơ sở dữ liệu mẫu
Nhấn phải vào Project chọn Properties:
Giờ thì bạn có thể sẵn sàng làm việc với một trong các Database ( Oracle, MySQL, SQL Server)
6- Connection
Trong tài liệu hướng dẫn này tôi sẽ hướng dẫn các kết nối vào cả 3 loại database:
● MySQL
● SQLServer
● Oracle
ConnectionUtils.java
?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11
12
13
public class ConnectionUtils {
14
15
16
17
18 public static Connection getMyConnection() throws SQLException,
19
20
ClassNotFoundException {
21
22
23 // Sử dụng Oracle.
24
25 // Bạn có thể thay thế bởi Database nào đó.
26
27
return OracleConnUtils.getOracleConnection();
28
29
30 }
31
//
//
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
System.out.println("Done!");
OracleConnUtils.java
?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class OracleConnUtils {
17
18
19
20
// Kết nối vào ORACLE.
21
22
23 public static Connection getOracleConnection() throws SQLException,
24
25 ClassNotFoundException {
26
27
String hostName = "localhost";
28
29
30 String sid = "db11g";
31
32 String userName = "simplehr";
33
34
String password = "simplehr";
35
36
37
38
return getOracleConnection(hostName, sid, userName, password);
}
SQLException {
// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.
Class.forName("oracle.jdbc.driver.OracleDriver");
// Ví dụ: jdbc:oracle:thin:@localhost:1521:db11g
return conn;
MySQLConnUtils.java
?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class MySQLConnUtils {
17
18
19
20
// Kết nối vào MySQL.
21
22
23 public static Connection getMySQLConnection() throws SQLException,
24
25 ClassNotFoundException {
26
27
String hostName = "localhost";
28
29
30
31
32 String dbName = "simplehr";
33
34
String userName = "root";
35
36
37 String password = "1234";
38
return getMySQLConnection(hostName, dbName, userName, password);
ClassNotFoundException {
// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.
Class.forName("com.mysql.jdbc.Driver");
// Ví dụ: jdbc:mysql://localhost:3306/simplehr
return conn;
SQLServerConnUtils_JTDS.java
?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class SQLServerConnUtils_JTDS {
17
18
19
20
21
22
23 // Kết nối vào SQLServer.
24
25 // (Sử dụng thư viện điều khiển JTDS)
26
27
public static Connection getSQLServerConnection()
28
29
30 throws SQLException, ClassNotFoundException {
31
32 String hostName = "localhost";
33
34
String sqlInstanceName = "SQLEXPRESS";
35
36
37 String database = "simplehr";
38
39 String userName = "sa";
40
41
42
43 String password = "1234";
44
45
46
47
return getSQLServerConnection(hostName, sqlInstanceName, database,
userName, password);
// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
// Cấu trúc URL Connection dành cho SQLServer
// Ví dụ:
// jdbc:jtds:sqlserver://localhost:1433/simplehr;instance=SQLEXPRESS
password);
return conn;
SQLServerConnUtils_SQLJDBC.java
?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class SQLServerConnUtils_SQLJDBC {
17
18
19
20
// Kết nối vào SQLServer.
21
22
23 // (Sử dụng thư viện điều khiển SQLJDBC)
24
25 public static Connection getSQLServerConnection()
26
27
throws SQLException, ClassNotFoundException {
28
29
30 String hostName = "localhost";
31
32 String sqlInstanceName = "SQLEXPRESS";
33
34
String database = "simplehr";
35
36
37 String userName = "sa";
38
39 String password = "1234";
40
41
42
43
44
45 return getSQLServerConnection(hostName, sqlInstanceName,
// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// jdbc:sqlserver://ServerIp:1433/SQLEXPRESS;databaseName=simplehr
password);
return conn;
ODBCConnUtils.java
?
1
2 package org.o7planning.tutorial.jdbc;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.DriverManager;
10
11 import java.sql.SQLException;
12
13
14
15
16 public class ODBCConnUtils {
17
18
19
20
// Lấy ra kết nối vào ODBC Data Source có tên "simplehr-ds".
21
22
23 public static Connection getJdbcOdbcConnection() throws SQLException,
24
25 ClassNotFoundException {
26
27
String odbcDataSourceName = "simplehr-ds";
28
29
30 String userName = "simplehr";
31
32 String password = "simplehr";
33
34
return getJdbcOdbcConnection(odbcDataSourceName, userName, password);
35
}
public static Connection getJdbcOdbcConnection(String odbcDataSourceName,
ClassNotFoundException {
// Nếu bạn dùng Java6, thì ko cần dòng này cũng được.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
password);
return conn;
}
}
Bạn có thể thay đổi Class ConnectionUtils để sử dụng kết nối tới một Database nào đó quen thuộc.
Và chạy class này để test kết nối.
● Hướng dẫn cài đặt và cấu hình SQL Server Express 2014
** ResultSet **
1
2 public String getString(int columnIndex) throws SQLException;
3
4 public boolean getBoolean(int columnIndex) throws SQLException;
5
6
public int getInt(int columnIndex) throws SQLException;
7
8
9 public double getDouble(int columnIndex) throws SQLException;
10
11
12
13
...
....
Ví dụ minh họa:
QueryDataExample.java
?
1
2 package org.o7planning.tutorial.jdbc.basic;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.ResultSet;
10
11 import java.sql.SQLException;
12
13
import java.sql.Statement;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class QueryDataExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32
33
34
// Lấy ra đối tượng Connection kết nối vào DB.
35
36
37 Connection connection = ConnectionUtils.getMyConnection();
38
39
40
// Tạo đối tượng Statement.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {// Di chuyển con trỏ xuống bản ghi kế tiếp.
System.out.println("--------------------");
System.out.println("EmpId:" + empId);
System.out.println("EmpNo:" + empNo);
System.out.println("EmpName:" + empName);
}
connection.close();
?
1
2 public Statement createStatement(int resultSetType, int resultSetConcurrency)
3
4 throws SQLException;
5
6
7
8
9 // Ví dụ:
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery(sql);
resultSetType Ý nghĩa
TYPE_FORWARD_ON - ResultSet c hỉ cho phép duyệt từ trên xuống dưới, từ trái sang phải. Đây
LY là kiểu mặc định của các ResultSet.
TYPE_SCROLL_INSE - ResultSet c ho phép cuộn tiến lùi, sang trái, sang phải, nhưng không
NSITIVE nhạy với các sự thay đổi dữ liệu dưới DB. Nghĩa là trong quá trình duyệt
qua một bản ghi và lúc nào đó duyệt lại bản ghi đó, nó không lấy các dữ
liệu mới nhất của bản ghi mà có thể bị ai đó thay đổi.
TYPE_SCROLL_SENS - ResultSet c ho phép cuộn tiến lùi, sang trái, sang phải, và nhạy cảm với
ITIVE sự thay đổi dữ liệu.
resultSetConcurr Ý nghĩa
ency
CONCUR_READ_ - Khi duyệt dữ liệu với các ResultSet kiểu này bạn chỉ có thể đọc dữ liệu.
ONLY
CONCUR_UPDAT - Khi duyệt dữ liệu với các ResultSet kiểu này bạn chỉ có thể thay đổi dữ liệu
ABLE tại nơi con trỏ đứng, ví dụ update giá trị cột nào đó.
ScrollableResultSetExample.java
?
1
2 package org.o7planning.tutorial.jdbc.basic;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.ResultSet;
10
11 import java.sql.SQLException;
12
13
import java.sql.Statement;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class ScrollableResultSetExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32
33
34
// Lấy ra đối tượng Connection kết nối tới DB.
35
36
37 Connection connection = ConnectionUtils.getMyConnection();
38
39
40
41
42
43 // Tạo một đối tượng Statement
44
45 // Có thể cuộn dữ liệu, nhưng không nhậy với các thay đổi dưới DB.
46
47
// Con trỏ chỉ có khả năng đọc, không có khả năng update dữ liệu trong quá trình
48
duyệt.
49
50
51 Statement statement = connection.createStatement(
52
53 ResultSet.TYPE_SCROLL_INSENSITIVE,
54 ResultSet.CONCUR_READ_ONLY);
55
56
57
58
59 String sql = "Select Emp_Id, Emp_No, Emp_Name from Employee";
60
61
62
63
// Thực thi câu lệnh SQL trả về đối tượng ResultSet.
64
65
66 ResultSet rs = statement.executeQuery(sql);
67
68
69
70
71
72
73 // Nhẩy con trỏ tới cuối
System.out.println("EmpId:" + rs.getInt(1));
System.out.println("EmpNo:" + rs.getString(2));
System.out.println("EmpName:" + rs.getString(3));
System.out.println("--------------------");
previous =rs.previous();
System.out.println("Previous 2: "+ previous);
while (rs.next()) {
System.out.println("--------------------");
System.out.println("EmpId:" + empId);
System.out.println("EmpNo:" + empNo);
System.out.println("EmpName:" + empName);
}
// Đóng kết nối
connection.close();
9- Ví dụ Insert dữ liệu
InsertDataExample.java
?
1
2 package org.o7planning.tutorial.jdbc.basic;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11 import java.sql.Statement;
12
13
14
15
16 import org.o7planning.tutorial.jdbc.ConnectionUtils;
17
18
19
20
public class InsertDataExample {
21
22
23
24
25 public static void main(String[] args) throws ClassNotFoundException,
26
27
SQLException {
28
29
30
PreparedStatement sử dụng để chuẩn bị trước các câu lệnh SQL, và tái sử dụng nhiều lần, giúp cho
chương trình thực hiện nhanh hơn.
PrepareStatementExample.java
?
1
2 package org.o7planning.tutorial.jdbc.pareparedstatement;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class PrepareStatementExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32 // Lấy ra kết nối tới cơ sở dữ liệu.
33
34
Connection connection = ConnectionUtils.getMyConnection();
35
36
37
38
39 // Tạo một câu SQL có 2 tham số (?)
40
41
42
43 String sql = "Select emp.Emp_Id, emp.Emp_No, emp.Emp_Name, emp.Dept_Id
44 from Employee emp "
45
46 + " where emp.Emp_Name like ? and emp.Dept_Id = ? ";
47
48
49
50
51 // Tạo một đối tượng PreparedStatement.
52
53 PreparedStatement pstm = connection.prepareStatement(sql);
54
55
56
// Sét đặt giá trị tham số thứ nhất (Dấu ? thứ nhất)
pstm.setString(1, "%S");
// Sét đặt giá trị tham số thứ hai (Dấu ? thứ hai)
pstm.setInt(2, 20);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
System.out.println();
pstm.setString(1, "KI%");
pstm.setInt(2,10);
rs = pstm.executeQuery();
while (rs.next()) {
11- CallableStatement
CallableStatement được xây dựng để gọi một thủ tục (procedure) hoặc hàm (function) của SQL.
1
2 // Câu lệnh gọi thủ tục SQL trên Java
3
4 String sql = "{call procedure_name(?,?,?)}";
5
// Câu lệnh gọi một hàm SQL trên Java
Để làm ví dụ với CallableStatement chúng ta cần một hàm hoặc một thủ tục trong DB. Với Oracle,
MySQL hoặc SQLServer b ạn có thể tạo nhanh một thủ tục như dưới đây:
● ORACLE
Get_Employee_Info
1
2 -- Thủ tục lấy ra thông tin của một nhân viên,
3
4 -- Truyền vào tham số p_Emp_ID (Integer)
5
6
-- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date
7
8
9
10
11 Create Or Replace Procedure Get_Employee_Info(p_Emp_Id Integer
12
13
,v_Emp_No Out Varchar2
14
15
16 ,v_First_Name Out Varchar2
Begin
--
v_First_Name := 'Michael';
v_Last_Name := 'Smith';
v_Hire_Date := Sysdate;
End Get_Employee_Info;
● MySQL
Get_Employee_Info
1
2 -- Thủ tục lấy ra thông tin của một nhân viên,
3
4 -- Truyền vào tham số p_Emp_ID (Integer)
5
6
-- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date
7
8
9
10
11 CREATE PROCEDURE get_Employee_Info(p_Emp_ID Integer,
12
13
out v_Emp_No Varchar(50) ,
14
15
16 out v_First_Name Varchar(50) ,
BEGIN
END
● SQL Server
Get_Employee_Info
1
2 -- Thủ tục lấy ra thông tin của một nhân viên,
3
4 -- Truyền vào tham số p_Emp_ID (Integer)
5
6
-- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date
7
8
9
10
11 CREATE PROCEDURE Get_Employee_Info
12
13
@p_Emp_Id Integer ,
14
15
16 @v_Emp_No Varchar(50) OUTPUT,
17
18 @v_First_Name Varchar(50) OUTPUT,
@v_Hire_DateDate OUTPUT
AS
BEGIN
--
END
CallableStatementExample.java
?
1
2 package org.o7planning.tutorial.jdbc.callablestatement;
3
4
5
6
import java.sql.CallableStatement;
7
8
9 import java.sql.Connection;
10
11 import java.sql.Date;
12
13
import java.sql.SQLException;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class CallableStatementExample {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
29
30 SQLException {
31
32 // Lấy ra kết nối tới cơ sở dữ liệu.
33
34
Connection connection = ConnectionUtils.getMyConnection();
35
36
37
38
39 // Câu lệnh gọi thủ tục (***)
40
41
42
43 String sql = "{call get_Employee_Info(?,?,?,?,?)}";
44
45
46
47
// Tạo một đối tượng CallableStatement.
48
49
50 CallableStatement cstm = connection.prepareCall(sql);
51
52
53
54
// Truyền tham số vào hàm (p_Emp_ID)
55
56
57 // (Là dấu chấm hỏi thứ 1 trên câu lệnh sql ***)
cstm.setInt(1, 10);
// (v_Emp_No)
cstm.registerOutParameter(2, java.sql.Types.VARCHAR);
// (v_First_Name)
cstm.registerOutParameter(3, java.sql.Types.VARCHAR);
// Đăng ký nhận giá trị trả về tại dấu hỏi thứ 4
// (v_Last_Name)
cstm.registerOutParameter(4, java.sql.Types.VARCHAR);
// (v_Hire_Date)
cstm.registerOutParameter(5, java.sql.Types.DATE);
cstm.executeUpdate();
Ví dụ người A chuyển một khoản tiền 1000$ vào tài khoản người B như vậy trong Database diễn ra 2
quá trình:
Và giao dịch được gọi là thành công nếu cả 2 bước kia thành công. Ngược lại chỉ cần 1 trong hai
bước hỏng là coi như giao dịch không thành công, phải rollback lại trạng thái ban đầu.
TransactionExample.java
?
1
2 package org.o7planning.tutorial.transaction;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11
12
13
import org.o7planning.tutorial.jdbc.ConnectionUtils;
14
15
16
17
18 public class TransactionExample {
19
20
21
22
23 private static void doJob1(Connection conn) {
24
25 // Làm gì đó tại đây.
26
27
// Insert update dữ liêu.
28
29
30 }
31
32
33
34
private static void doJob2(Connection conn) {
35
36
37 // Làm gì đó tại đây.
38
39 // Insert update dữ liêu.
40
41
42
43 }
44
45
46
47
public static void main(String[] args) throws ClassNotFoundException,
48
49
50 SQLException {
connection.setAutoCommit(false);
try {
doJob1(connection);
doJob2(connection);
// Gọi method commit dữ liệu xuống DB.
connection.commit();
catch (Exception e) {
e.printStackTrace();
// Rollback dữ liệu
connection.rollback();
// Đóng Connection.
connection.close();
BatchExample.java
?
1
2 package org.o7planning.tutorial.transaction;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.SQLException;
10
11 import java.sql.Statement;
12
13
14
15
16 import org.o7planning.tutorial.jdbc.ConnectionUtils;
17
18
19
20
public class BatchExample {
21
22
23
24
25 public static void main(String[] args) throws SQLException,
26
27
ClassNotFoundException {
28
29
30
31
32 Connection conn = ConnectionUtils.getMyConnection();
33
34
35
36
37 try {
38
39 // Create statement object
40
41
42
43 Statement stmt = conn.createStatement();
44
45
46
47
// Set auto-commit to false
48
49
50 conn.setAutoCommit(false);
51
52
53
54
// Create SQL statement
55
56
57 // Tạo câu lệnh Insert dữ liệu vào bảng Employee
58
59 String sql1 = "Update Employee emp set emp.Salary = emp.Salary + 100 "
60
stmt.addBatch(sql1);
stmt.addBatch(sql2);
// Thêm vào lô
stmt.addBatch(sql3);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
conn.rollback();
BatchExample2.java
?
1
2 package org.o7planning.tutorial.transaction;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.Date;
10
11 import java.sql.PreparedStatement;
12
13
import java.sql.SQLException;
14
15
16 import java.util.UUID;
17
18
19
20
import org.o7planning.tutorial.jdbc.ConnectionUtils;
21
22
23
24
25 public class BatchExample2 {
26
27
28
29
30 public static void main(String[] args) throws ClassNotFoundException,
31
32 SQLException {
33
34
35
36
37 Connection conn = ConnectionUtils.getMyConnection();
38
39
40
41
42
43 try {
44
45 String sql = "Insert into Timekeeper(Timekeeper_Id, Date_Time, In_Out,
46 Emp_Id) "
47
48
+ " values (?,?,?,?) ";
49
50
51 // Create statement object
52
53 PreparedStatement stmt = conn.prepareStatement(sql);
54
55
56
57
58 // Set auto-commit to false
conn.setAutoCommit(false);
stmt.setString(1, UUID.randomUUID().toString());
stmt.setString(3, "I");
stmt.setInt(4, 7839);
stmt.addBatch();
// Sét đặt các giá trị tham số khác
stmt.setString(1, UUID.randomUUID().toString());
stmt.setString(3, "I");
stmt.setInt(4, 7566);
stmt.addBatch();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
conn.rollback();
Java cơ bản
Mục lục
1- Vấn đề
2- Lấy giá trị cột ID của bản ghi vừa được trèn
Java cơ bản
Lấy các giá trị của các cột tự động tăng khi Insert một bản ghi sử dụng
JDBC
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
ấn đề
1- V
1- Vấn đề
Trong một số cơ sở dữ liệu, Cột ID c ủa một bảng có thể là kiểu mà giá trị tự động tăng. Mỗi khi trèn
một bản ghi (record) vào bảng, giá trị của cột này sẽ được gán bởi database, bạn không thể chủ động
chỉ định một giá trị cho nó. Câu hỏi của bạn là trong trường hợp này làm thế nào để lấy được ID c ủa
bản ghi vừa được trèn vào.
Ngoài ra một số cột có thể không tham gia trong câu lệnh Insert của bạn, trong trường hợp đó giá trị
của nó được gán mặc định bởi database, bạn muốn lấy ra các giá trị này mà không cần thiết phải tạo
thêm một lệnh truy vấn.
PostGres
Trong PostGres, cột có kiểu Serial s ẽ có giá trị tự động tăng bởi database.
** Employees (PostGres) **
1
2 CREATE TABLE Employees
3
4 (
5
6
ID serial NOT NULL,
7
8
9 Full_Name character varying(50) NOT NULL,
);
MySQL
Trong MySQL, để một cột có giá trị tự động tăng nó phải được gán thuộc tính (attribute)
"Auto_Increase".
** Employees (MySQL) **
?
1
2 CREATE TABLE Employees
3
4 (
5
6
ID Int Auto_Increase NOT NULL,
7
8
Full_Name Varchar(50) NOT NULL,
);
2- Lấy giá trị cột ID của bản ghi vừa được trèn
Khi bạn sử dụng JDBC đ ể Insert m ột bản ghi vào database. Cột ID có thể không tham gia vào trong
câu lệnh Insert. Vị trí của cột ID đ ược xác định bởi thiết kế của bảng đó. Cột đầu tiên có chỉ số 1, cột
thứ 2 có chỉ số 2,...
GeneratedIDValueExample.java
?
1
2 package org.o7planning.tutorial.jdbc.others;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16 import java.sql.Statement;
17
18
19
20
import org.o7planning.tutorial.jdbc.ConnectionUtils;
21
22
23
24
25 public class GeneratedIDValueExample {
26
27
28
29
30 public static void main(String[] args) throws ClassNotFoundException,
31 SQLException {
32
33 // Lấy ra kết nối tới cơ sở dữ liệu.
34
35
Connection conn = ConnectionUtils.getMyConnection();
36
37
38
39
40 // Employees (id, full_name, gender, hire_date)
41
42
43 // ID: Auto Increase
44
45 String sql = "Insert into Employees " //
pstm.setString(1, "Tran");
pstm.setString(2, "M");
// Execute!
pstm.execute();
ResultSet rs = pstm.getGeneratedKeys();
int idValue = 0;
if (rs.next()) {
idValue = rs.getInt(1);
Chỉ số của cột ID của bảng có thể không phải là 1 (Tùy thuộc vào thiết kế của bảng). Trong trường
hợp này tốt nhất bạn truy cập giá trị của nó theo tên.
GeneratedIDValueExample2.java
?
1
2 package org.o7planning.tutorial.jdbc.others;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16 import java.sql.Statement;
17
18
19
20
import org.o7planning.tutorial.jdbc.ConnectionUtils;
21
22
23
24
25 public class GeneratedIDValueExample2 {
26
27
28
29
30 public static void main(String[] args) throws ClassNotFoundException,
31 SQLException {
32
33
34
35
Connection conn = ConnectionUtils.getMyConnection();
36
37
38
39
40 // Employees (id, full_name, gender, hire_date)
41
42
43 // ID: Auto Increase
44
45 String sql = "Insert into Employees " //
46
47
+ " (full_name, gender, hire_date) " //
pstm.setString(1, "Tran");
pstm.setString(2, "M");
// Execute!
pstm.execute();
ResultSet rs = pstm.getGeneratedKeys();
int idValue = 0;
if (rs.next()) {
// Chú ý với một số DB, tên cột phân biệt chữ hoa chữ thường.
idValue = rs.getInt("id");
?
1
2 package org.o7planning.tutorial.jdbc.others;
3
4
5
6
import java.sql.Connection;
7
8
9 import java.sql.PreparedStatement;
10
11 import java.sql.ResultSet;
12
13
import java.sql.SQLException;
14
15
16
17
18 import org.o7planning.tutorial.jdbc.ConnectionUtils;
19
20
21
22
23 public class GetGeneratedValueExample2 {
24
25
26
27
public static void main(String[] args) throws ClassNotFoundException,
28
SQLException {
29
30
31
32
33 Connection conn = ConnectionUtils.getMyConnection();
34
35
36
37
38 // Employees (id, full_name, gender, hire_date)
39
40 // ID: Auto Increase
41
42
43 // gender: Default
44
45 String sql = "Insert into Employees " //
46
47
+ " (Full_Name, Hire_Date) " //
48
pstm.setString(1, "Tran");
// Execute!
pstm.execute();
ResultSet rs = pstm.getGeneratedKeys();
int idValue = 0;
if (rs.next()) {
idValue = rs.getInt("ID");
gender = rs.getString("Gender");
hireDate = rs.getDate("Hire_Date");
System.out.println("ID value: " + idValue + " Gender: " + gender + ", Hidedate: " +
hireDate);
Java cơ bản
Mục lục
Java cơ bản
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
ử lý file RAR
3- X
Đáng tiếc là thư viện này không thể đọc và giải nén các định dạng phổ biến khác như rar, hoặc 7zip.
Để giải sử lý các định dạng rar, 7zip, .. bạn cần có một thư viện khác. Trong tài liệu này tôi có để cập
tới các thư viện để làm việc này.
Đây là hình ảnh một file zip được mở bằng công cụ Winrar.
?
1
2 package org.o7planning.tutorial.javaiozip;
3
4
5
6
import java.io.FileInputStream;
7
8
9 import java.util.zip.ZipEntry;
10
11 import java.util.zip.ZipInputStream;
12
13
14
15
16 public class ListZipEntriesDemo {
17
18
19
20
public static void main(String[] args) {
21
22
23 String FILE_PATH = "C:/test/datas.zip";
24
25
26
27
ZipInputStream zipIs = null;
28
29
30 try {
31
32 // Tạo đối tượng ZipInputStream để đọc file zip.
33
34
zipIs = new ZipInputStream(new FileInputStream(FILE_PATH));
35
36
37
38
ZipEntry entry = null;
// Duyệt từng Entry (Từ trên xuống dưới cho tới hết)
if (entry.isDirectory()) {
System.out.print("Directory: ");
} else {
System.out.print("File: ");
System.out.println(entry.getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
zipIs.close();
} catch (Exception e) {
}
}
Ví dụ giải nén file zip vào một thư mục nào đó:
UnZipDemo.java
?
1
2 package org.o7planning.tutorial.javaiozip;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileInputStream;
10
11 import java.io.FileOutputStream;
12
13
import java.util.zip.ZipEntry;
14
15
16 import java.util.zip.ZipInputStream;
17
18
19
20
public class UnZipDemo {
21
22
23
24
25 public static void main(String[] args) {
26
27
final String OUTPUT_FOLDER = "C:/output";
28
29
30 String FILE_PATH = "C:/test/datas.zip";
31
32
33
34
// Tạo thư mục Output nếu nó không tồn tại.
35
36
37 File folder = new File(OUTPUT_FOLDER);
38
39 if (!folder.exists()) {
40
41
42
43 folder.mkdirs();
44
45 }
46
47
// Tạo một buffer (Bộ đệm).
48
49
50 byte[] buffer = new byte[1024];
51
52
53
54
ZipInputStream zipIs = null;
55
56
57 try {
58
59 // Tạo đối tượng ZipInputStream để đọc file từ 1 đường dẫn (path).
60
61
zipIs = new ZipInputStream(new FileInputStream(FILE_PATH));
62
// Duyệt từng Entry (Từ trên xuống dưới cho tới hết)
new File(outFileName).mkdirs();
} else {
int len;
fos.write(buffer, 0, len);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
zipIs.close();
} catch (Exception e) {
?
1
2 package org.o7planning.tutorial.javaiozip;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileInputStream;
10
11 import java.io.FileOutputStream;
12
13
import java.io.IOException;
14
15
16 import java.io.OutputStream;
17
18 import java.util.ArrayList;
19
20
import java.util.List;
21
22
23 import java.util.zip.ZipEntry;
24
25 import java.util.zip.ZipOutputStream;
26
27
28
29
30 public class ZipDirectory {
31
32
33
34
public ZipDirectory() {
35
36
37
38
39 }
40
41
42
43
44
45 // Phương thức dùng để nén một thư mục.
46
47
public void zipDirectory(File inputDir, File outputZipFile) {
48
49
50 // Tạo thư mục cha cho file đầu ra (output file).
51
52 outputZipFile.getParentFile().mkdirs();
53
54
55
56
57 String inputDirPath = inputDir.getAbsolutePath();
58
59 byte[] buffer = new byte[1024];
60
61
62
63
64 FileOutputStream fileOs = null;
65
66 ZipOutputStream zipOs = null;
67
68
try {
69
70
71
72
73 List<File> allFiles = this.listChildFiles(inputDir);
74
75
76
77
78 // Tạo đối tượng ZipOutputStream để ghi file zip.
79
80 fileOs = new FileOutputStream(outputZipFile);
81
82
83
84 //
85
86 zipOs = new ZipOutputStream(fileOs);
87
88
for (File file : allFiles) {
89
90
91 String filePath = file.getAbsolutePath();
92
93
94
95
System.out.println("Zipping " + filePath);
96
97
98 // entryName: is a relative path.
zipOs.putNextEntry(ze);
int len;
fileIs.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeQuite(zipOs);
closeQuite(fileOs);
try {
out.close();
} catch (Exception e) {
}
// bao gồm tất cả các file con, cháu,.. của thư mục đầu vào.
if (file.isFile()) {
allFiles.add(file);
} else {
allFiles.addAll(files);
}
return allFiles;
zipDir.zipDirectory(inputDir, outputZipFile);
Về cơ bản việc đọc ghi file jar k hông có gì khác biệt so với file Zip.
ở rộng từ ZipInputStream hỗ trợ thêm tính năng đọc các thông tin
● JarInputStream m
MANIFEST.
● JarOutputStream m ở rộng từ ZipOutputStream h ỗ trợ thêm tính năng ghi thông tin
MANIFEST.
Các file thư viện jar thông thường của java thường có thông tin MANIFEST rất đơn giản.
Ví dụ đây là một file MANIFEST.MF đóng gói trong file jar của 1 ứng dụng RAP có nhiều thông tin
hơn:
META-INF/MANIFEST.MF
?
1
2 Manifest-Version: 1.0
3
4 Bundle-ManifestVersion: 2
5
6
Bundle-Name: RAPWorkbenchTutorial
7
8
9 Bundle-SymbolicName: RAPWorkbenchTutorial;singleton:=true
10
11 Bundle-Version: 1.0.0.qualifier
12
13
Bundle-Activator: rapworkbenchtutorial.Activator
14
15
16 Require-Bundle: org.eclipse.rap.ui;bundle-version="2.3.0",
17
org.apache.felix.gogo.command;bundle-version="0.10.0",
org.apache.felix.gogo.runtime;bundle-version="0.10.0",
org.apache.felix.gogo.shell;bundle-version="0.10.0",
org.eclipse.equinox.console;bundle-version="1.1.0",
org.eclipse.equinox.http.jetty;bundle-version="3.0.200",
org.eclipse.equinox.ds;bundle-version="1.4.200",
org.eclipse.rap.rwt.osgi;bundle-version="2.3.0",
org.eclipse.rap.design.example;bundle-version="2.3.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-ActivationPolicy: lazy
Một ví dụ đơn giản đọc thông tin MANIFEST của file jar. Dưới đây là hình ảnh nội dung của một file
Manifest đơn giản.
ReadJarFileDemo.java
?
1
2 package org.o7planning.tutorial.jar;
3
4
5
6
import java.io.FileInputStream;
7
8
9 import java.util.jar.Attributes;
10
11 import java.util.jar.JarEntry;
12
13
import java.util.jar.JarInputStream;
14
15
16 import java.util.jar.Manifest;
17
18
19
20
public class ReadJarFileDemo {
21
22
23
24
25 public static void main(String[] args) {
26
27
String FILE_PATH = "C:/DevPrograms/Java/jdk1.7.0_45/lib/dt.jar";
28
29
30
31
32 JarInputStream zipIs = null;
33
34
try {
35
36
37 // Tạo đối tượng JarInputStream để đọc file jar.
38
39 zipIs = new JarInputStream(new FileInputStream(FILE_PATH));
40
41
42
43
44
45 // Đọc thông tin Manifest:
46
47
Manifest manifest = zipIs.getManifest();
48
49
Attributes atts = manifest.getMainAttributes();
System.out.println("Manifest-Version:" + version);
System.out.println("Created-By:" + createdBy);
System.out.println("========================");
// Duyệt từng Entry (Từ trên xuống dưới cho tới hết)
if (entry.isDirectory()) {
System.out.print("Folder: ");
} else {
System.out.print("File: ");
}
System.out.println(entry.getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
zipIs.close();
} catch (Exception e) {
1. JUnRar:
2. java-unrar
Trong tài liệu này tôi sẽ hướng dẫn bạn sử dụng JUnRar (Phiên bản tại thời điểm 9-2014 đang là
0.7)
● http://github.com/edmund-wagner/junrar
Download junrar:
● http://mvnrepository.com/artifact/com.github.junrar/junrar
Xem thêm các chuyên mục:
Java cơ bản
Mục lục
1- Java Reflection là gì ?
4- Class
5- Cấu tử (Constructor)
6- Trường (Field)
10- Annotation
Java cơ bản
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
1- Java Reflection là gì ?
ấu tử (Constructor)
5- C
rường (Field)
6- T
10- Annotation
1- Java Reflection là gì ?
Java sử dụng từ "Java Reflection" để đặt tên cho một API quan trọng trong thư viện chuẩn của
Java. Tại sao API này lại được đặt tên như vậy? Chúng hãy cùng phân tích ý nghĩa của việc này.
Reflection chính là một hình ảnh phản chiếu của một vật thể. Chẳng hạn hình ảnh của bạn trong một
tấm gương, hoặc ảnh phản xạ của một cái cây trên mặt hồ. Từ "Java Reflection" đơn giản là đang
ám chỉ một hình ảnh khác, một cách tiếp cận khác của Java.
Java là một ngôn ngữ hướng đối tượng (Object-oriented), thông thường bạn cần tạo ra một đối tượng
và bạn có thể truy cập vào các trường (field), hoặc gọi phương thức (method) của đối tượng này
thông qua toán tử dấu chấm ( . )
Java Reflection giới thiệu một cách tiếp cận khác, bạn có thể truy cập vào một trường của một đối
tượng nếu bạn biết tên của trường đó. Hoặc bạn có thể gọi một phương thức của đối tượng nếu bạn
biết tên phương thức, các kiểu tham số của phương thức, và các giá trị tham số để truyền vào ...
Java Reflecion cho phép bạn đánh giá, sửa đổi cấu trúc và hành vi của một đối tượng tại thời gian
chạy (runtime) của chương trình. Đồng thời nó cho phép bạn truy cập vào các thành viên private
(private member) tại mọi nơi trong ứng dụng, điều này không được phép với cách tiếp cận truyền
thống.
1. Java t hông thường có thể được gọi là Java Introspection (Nội quan), chương trình có khả
năng đánh giá cấu trúc của một đối tượng tại thời gian chạy (Runtime).
2. Với Java Reflection, chương trình có khả năng đánh giá cấu trúc của một đối tượng tại thời
gian chạy, sửa đổi cấu trúc và hành vi của đối tượng.
Animal.java
?
1
2 package org.o7planning.tutorial.beans;
3
4
5
6
public abstract class Animal {
7
8
9
10
11
12
return "Earth";
Say.java
1
2 package org.o7planning.tutorial.beans;
3
4
5
6
public interface Say {
public String say();
Cat.java
?
1
2 package org.o7planning.tutorial.beans;
3
4
5
6
7
8
9 public class Cat extends Animal implements Say {
10
11
12
13
public static final String SAY = "Meo meo";
14
15
16 public static final int NUMBER_OF_LEGS = 4;
17
18
19
20
// Private field.
21
22
23 private String name;
24
25
26
27
// Private field
28
29
30 public int age;
31
32
33
34
public Cat() {
35
36
37
38
39 }
40
41
42
43
44
45 public Cat(String name) {
46
47
this.name = name;
48
49
50 this.age = 1;
51
52 }
53
54
55
56
57 public Cat(String name, int age) {
58
59 this.name = name;
60
61
this.age = age;
62
return this.name;
// Private Method.
return this.age;
this.age = age;
/**
*/
@Override
return SAY;
}
/**
*/
@Override
return NUMBER_OF_LEGS;
ListMethod.java
?
1
2 package org.o7planning.tutorial.reflect.helloreflect;
3
4
5
6
import java.lang.reflect.Method;
7
8
9
10
11 public class ListMethod {
12
13
14
15
16 // Protected method
17
18 protected void info() {
19
20
21
22
23 }
24
25
26
27
public static void testMethod1() {
28
29
30
31
}
// Bao gồm các các method thừa kế từ class cha, hoặc các interface.
Ví dụ ghi ra các thông tin cơ bản của class như tên class, package, modifier, ..
ShowClassInfo.java
?
1
2 package org.o7planning.tutorial.reflect.clazz;
3
4
5
6
import java.lang.reflect.Modifier;
7
8
9
10
11 public final class ShowClassInfo {
12
13
14
15
16 public static void main(String[] args) {
17
18
19
20
// Lấy ra đối tượng 'Class' mô tả class ShowClassInfo
21
22
23 Class<ShowClassInfo> aClass = ShowClassInfo.class;
24
25
26
27
// Ghi ra tên class, bao gồm cả tên package.
28
29
30 System.out.println("Class Name= " + aClass.getName());
31
32
33
34
// Ghi ra tên đơn giản của Class
35
36
37 System.out.println("Simple Class Name= " + aClass.getSimpleName());
38
39
40
// Thông tin Package.
// Modifier
// true
// true
// false
System.out.println("Is Interface? " + isInterface);
// false
Ví dụ ghi ra thông tin của class Cat, như tên class, và các Interface mà class này thi hành.
ShowClassCatInfo.java
?
1
2 package org.o7planning.tutorial.reflect.clazz;
3
4
5
6
import org.o7planning.tutorial.beans.Cat;
7
8
9
10
11 public class ShowClassCatInfo {
12
13
14
15
16 public static void main(String[] args) {
17
18
19
20
// Đối tượng Class mô tả class Cat.
21
22
23 Class<Cat> aClass = Cat.class;
24
25
26
27
// Tên class
28
29
System.out.println("Simple Class Name = " + aClass.getSimpleName());
+ aSuperClass.getSimpleName());
Ví dụ lấy ra thông tin các constructor, method, field của class (Chỉ public), bao gồm cả các public
method, public field, thừa kế từ các class cha, và các interace.
ShowMemberInfo.java
1
2 package org.o7planning.tutorial.reflect.clazz;
3
4
5
6
import java.lang.reflect.Constructor;
7
8
9 import java.lang.reflect.Field;
10
11 import java.lang.reflect.Method;
12
13
14
15
16 import org.o7planning.tutorial.beans.Cat;
17
18
19
20
public class ShowMemberInfo {
21
22
23
24
25 public static void main(String[] args) {
26
27
28
29
30 // Lấy ra đối tượng Class mô tả class Cat
31
32 Class<Cat> aClass = Cat.class;
33
34
35
36
37 // Lấy ra danh sách các cấu tử của Cat.
38
39
40 Constructor<?>[] constructors = aClass.getConstructors();
41
42
43
44
System.out.println(" ==== CONSTRUCTORs: ===== ");
}
// Lấy ra danh sách các field public
// Kể các các public field thừa kế từ các class cha, và các interface
Kết quả
5- Cấu tử (Constructor)
Ví dụ lấy ra một cấu tử với (constructor) các tham số chỉ định trước. Và ghi ra thông tin về cấu tử
(constructor) này.
ConstructorExample.java
?
1
2 package org.o7planning.tutorial.reflect.constructor;
3
4
5
6
import java.lang.reflect.Constructor;
7
8
9 import java.lang.reflect.InvocationTargetException;
10
11
12
13
import org.o7planning.tutorial.beans.Cat;
14
15
16
17
18 public class ConstructorExample {
19
20
21
22
23 public static void main(String[] args) throws NoSuchMethodException,
24
25 SecurityException, InstantiationException, IllegalAccessException,
26
27
IllegalArgumentException, InvocationTargetException {
28
29
30
31
32 // Lấy ra đối tượng Class mô tả class Cat
33
34
Class<Cat> aClass = Cat.class;
35
36
37
38
39 // Lấy ra cấu tử có tham số (String,int) của class Cat
Constructor<?> constructor = aClass.getConstructor(String.class,
int.class);
System.out
+ tom2.getAge());
6- Trường (Field)
Ví dụ dưới đây lấy ra field với tên chỉ định sẵn.
FieldExample.java
?
1
2 package org.o7planning.tutorial.reflect.field;
3
4
5
6
import java.lang.reflect.Field;
7
8
9
10
11 import org.o7planning.tutorial.beans.Cat;
12
13
14
15
16 public class FieldExample {
17
18
19
20
public static void main(String[] args) throws NoSuchFieldException,
21
22
23 SecurityException, IllegalArgumentException, IllegalAccessException {
24
25
26
27
// Lấy ra đối tượng Class mô tả class Cat
28
29
30 Class<Cat> aClass = Cat.class;
31
32
33
34
// Lấy ra field có tên 'NUMBER_OF_LEGS':
35
36
37 Field field = aClass.getField("NUMBER_OF_LEGS");
38
39
// Ghi ra kiểu của Field
// Lấy ra giá trị của trường "age" theo cách của Reflect.
ageField.set(tom, 7);
MethodExample.java
?
1
2 package org.o7planning.tutorial.reflect.method;
3
4
5
6
import java.lang.reflect.InvocationTargetException;
7
8
9 import java.lang.reflect.Method;
10
11
12
13
import org.o7planning.tutorial.beans.Cat;
14
15
16
17
18 public class MethodExample {
19
20
21
22
23 public static void main(String[] args) throws NoSuchMethodException,
24
25 SecurityException, IllegalAccessException,
26
27
IllegalArgumentException, InvocationTargetException {
28
29
30
31
32 // Lấy ra đối tượng Class mô tả class Cat
33
34
Class<Cat> aClass = Cat.class;
35
36
37
38
39 // Lấy ra đối tượng 'Method' mô tả method getAge()
40
41
42
Method getAgeMethod = aClass.getMethod("getAge");
setAgeMethod.invoke(tom, 5);
GetSetExample.java
?
1
2 package org.o7planning.tutorial.reflect.getset;
3
4
5
6
import java.lang.reflect.Method;
7
8
9
10
11 import org.o7planning.tutorial.beans.Cat;
12
13
14
15
16 public class GetSetExample {
17
18
19
20
// Method là getter nếu có tên bắt đầu bằng get, và không có tham số.
21
22
23 public static boolean isGetter(Method method) {
24
25 if (!method.getName().startsWith("get")) {
26
27
return false;
28
29
30 }
31
32 if (method.getParameterTypes().length != 0) {
33
34
return false;
35
36
37 }
38
39 if (void.class.equals(method.getReturnType())) {
40
41
42
43 return false;
44
45 }
46
47
return true;
48
49
50 }
51
52
53
// Method là setter nếu có tên bắt đầu bằng set, và chỉ có 1 tham số.
if (!method.getName().startsWith("set")) {
return false;
if (method.getParameterTypes().length != 1) {
return false;
return true;
}
public static void main(String[] args) {
}
}
?
1
2 Method: getName
3
4 - Is Setter? false
5
6
- Is Getter? true
7
8
9 Method: getNumberOfLegs
10
11 - Is Setter? false
12
13
- Is Getter? true
14
15
16 Method: getAge
17
18 - Is Setter? false
19
20
- Is Getter? true
21
22
23 Method: setAge
24
25 - Is Setter? true
26
27
- Is Getter? false
28
29
30 Method: say
31
32 - Is Setter? false
33
34
- Is Getter? false
35
36
37 Method: getLocation
38
39 - Is Setter? false
40
41
42
43 - Is Getter? true
44
45 Method: wait
46
47
- Is Setter? false
- Is Getter? false
Method: wait
- Is Setter? false
- Is Getter? false
Method: wait
- Is Setter? false
- Is Getter? false
Method: equals
- Is Setter? false
- Is Getter? false
Method: toString
- Is Setter? false
- Is Getter? false
Method: hashCode
- Is Setter? false
- Is Getter? false
Method: getClass
- Is Setter? false
- Is Getter? true
Method: notify
- Is Setter? false
- Is Getter? false
Method: notifyAll
- Is Setter? false
- Is Getter? false
Bạn không thể truy cập vào các method hay field mà nó là private theo cách thông thường, quá trình
biên dịch java cũng không cho phép điều đó. Nhưng với Java Reflection điều đó hoàn toàn có thể.
AccessPrivateFieldExample.java
?
1
2 package org.o7planning.tutorial.reflect.privateaccess;
3
4
5
6
import java.lang.reflect.Field;
7
8
9
10
11 import org.o7planning.tutorial.beans.Cat;
12
13
14
15
16 public class AccessPrivateFieldExample {
17
18
19
20
public static void main(String[] args) throws IllegalArgumentException,
21
22
23 IllegalAccessException, NoSuchFieldException, SecurityException {
24
25
26
27
// Tạo một đối tượng Class mô tả class Cat.
28
29
30 Class<Cat> aClass = Cat.class;
31
32
33
34
// Class.getField(String) chỉ lấy được các trường public.
35
36
// Sử dụng Class.getDeclaredField(String):
private_nameField.setAccessible(true);
}
}
AccessPrivateMethodExample.java
?
1
2 package org.o7planning.tutorial.reflect.privateaccess;
3
4
5
6
import java.lang.reflect.InvocationTargetException;
7
8
9 import java.lang.reflect.Method;
10
11
12
13
import org.o7planning.tutorial.beans.Cat;
14
15
16
17
18 public class AccessPrivateMethodExample {
19
20
21
22
23 public static void main(String[] args) throws NoSuchMethodException,
24
25 SecurityException, IllegalAccessException,
26
27
IllegalArgumentException, InvocationTargetException {
28
29
30
31
32 // Tạo một đối tượng Class mô tả class Cat.
33
34
Class<Cat> aClass = Cat.class;
35
36
37
String.class);
private_setNameMethod.setAccessible(true);
}
}
Kết quả
10- Annotation
MyAnnotation.java
?
1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.ElementType;
7
8
9 import java.lang.annotation.Retention;
10
11 import java.lang.annotation.RetentionPolicy;
12
13
import java.lang.annotation.Target;
14
15
16
17
18 // Annotation này có thể sử dụng tại thời điểm chạy (Runtime) của chương trình.
@Retention(RetentionPolicy.RUNTIME)
ElementType.PARAMETER })
String name();
ClassAnnotationExample.java
1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.Annotation;
7
8
9
10
11 @MyAnnotation(name = "Table", value = "Employee")
12
13
public class ClassAnnotationExample {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 Class<?> aClass = ClassAnnotationExample.class;
24
25
Kết quả:
FieldMethodAnnotationExample.java
?
1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.Annotation;
7
8
9 import java.lang.reflect.Field;
10
11 import java.lang.reflect.Method;
12
13
14
15
16 public class FieldMethodAnnotationExample {
17
18
19
20
@MyAnnotation(name = "My Field")
21
22
23 private int myField;
24
25
26
27
@MyAnnotation(name = "My Method", value = "My Method Value")
28
29
30 protected void myMethod(String str) {
31
32
33
34
}
35
36
37
38
39 public static void main(String[] args) throws NoSuchFieldException,
40
41
42
43 SecurityException, NoSuchMethodException {
44
45
46
47
Class<?> aClass = FieldMethodAnnotationExample.class;
48
49
50
51
52 //
53
54
System.out.println(" == FIELD == ");
55
56
57 Field field = aClass.getDeclaredField("myField");
58
59
60
61
// Lấy ra danh sách các Annotation của field.
62
System.out.println("Annotation: "
+ methodAnn.annotationType().getSimpleName());
// Lấy cụ thể.
System.out.println("Annotation: "
+ methodAnn.annotationType().getSimpleName());
}
// Lấy cụ thể.
ParameterAnnotationExample.java
?
1
2 package org.o7planning.tutorial.reflect.annotation;
3
4
5
6
import java.lang.annotation.Annotation;
7
8
9 import java.lang.reflect.Method;
10
11
12
13
public class ParameterAnnotationExample {
14
15
16
17
18 // Ví dụ một method có Annotation ở tham số.
19
20
protected void doSomething(int jobType,
21
22
23 @MyAnnotation(name = "Table", value = "Employee") String info) {
24
25
26
27
}
28
29
30
31
32 public static void main(String[] args) throws NoSuchMethodException,
33
34
SecurityException {
35
36
37
38
39 Class<?> aClass = ParameterAnnotationExample.class;
40
41
42
43
// Lấy ra đối tượng Method của method doSomething(int,String)
String.class);
+ parameterType.getSimpleName());
System.out.println("Annotation: "
+ ann.annotationType().getSimpleName());
Java cơ bản
Hướng dẫn gọi phương thức từ xa với Java RMI
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
iới thiệu
1- G
ạo project
2- T
1- Giới thiệu
RMI là một cách để bạn có thể gọi phương thức (method) từ xa, chẳng hạn gọi method đang chạy
trên một máy tính B. Và nhận kết quả trả về. Như vậy máy B giống như một máy chủ cung cấp dịch
vụ.
2- Tạo project
Tạo mới một project có tên RMITutorial
Đây là mô hình các class được đóng gói dành cho Client và Server
Đây là mô hình làm việc của RMI. Server sẽ đăng ký đối tượng lên trên bộ đăng ký (Registry). Client
sẽ tìm kiếm bộ đăng ký theo địa chỉ IP và cổng (Host + Port) để có thể gọi các các phương thức
(method) từ các đối tượng tại Server.
Constants.java
1
2 package org.o7planning.tutorial.rmi;
3
4
5
6
public class Constants {
7
8
9
10
11 // Địa điểm Hà Nội
12
13
public static final String LOCATION_HANOI = "HaNoi";
14
15
16 public static final String LOCATION_TOKYO = "Tokyo";
17
public static final String LOCATION_CHICAGO = "Chicago";
WeatherData.java
?
1
2 package org.o7planning.tutorial.rmi;
3
4
5
6
import java.io.Serializable;
7
8
9 import java.util.Date;
10
11
12
13
public class WeatherData implements Serializable {
14
15
16
17
18 private static final long serialVersionUID = 1L;
19
20
21
22
23 private Date date;
24
25 private String location;
26
27
private String weather;
28
29
30
31
32 public WeatherData(Date date, String location, String weather) {
33
34
this.date = date;
35
36
37 this.location = location;
38
39 this.weather = weather;
40
41
42
43 }
44
return date;
this.date = date;
return location;
this.location = location;
}
public String getWeather() {
return weather;
this.weather = weather;
WeatherService.java
1
2 package org.o7planning.tutorial.rmi;
3
4
5
6
import java.rmi.Remote;
7
8
9 import java.rmi.RemoteException;
10
11 import java.util.Date;
12
13
14
15
throws RemoteException;
WeatherServiceImpl.java
?
1
2 package org.o7planning.tutorial.rmi.server;
3
4
5
6
import java.rmi.RemoteException;
7
8
9 import java.rmi.server.UnicastRemoteObject;
10
11 import java.util.Calendar;
12
13
import java.util.Date;
14
15
16
17
18 import org.o7planning.tutorial.rmi.Constants;
19
20
import org.o7planning.tutorial.rmi.WeatherData;
21
22
23 import org.o7planning.tutorial.rmi.WeatherService;
24
25
26
27
public class WeatherServiceImpl extends UnicastRemoteObject implements
28
29
30 WeatherService {
31
32 private static final long serialVersionUID = 1L;
33
34
35
36
37 public WeatherServiceImpl() throws RemoteException {
38
39 super();
40
41
42
43 }
44
45
46
@Override
throws RemoteException {
Calendar c = Calendar.getInstance();
c.setTime(date);
// Sunday, Monday
if (dayOfWeek == 1 || dayOfWeek == 2) {
if (location.equals(Constants.LOCATION_CHICAGO)) {
// Rain
} else if (location.equals(Constants.LOCATION_HANOI)) {
// Sunny
return new WeatherData(date, location, Constants.WEATHER_SUNNY);
} else if (location.equals(Constants.LOCATION_TOKYO)) {
// Sunny
} else {
Client.java
?
1
2 package org.o7planning.tutorial.rmi.client;
3
4
5
6
import java.rmi.registry.LocateRegistry;
7
8
9 import java.rmi.registry.Registry;
10
11 import java.util.Date;
12
13
14
15
16 import org.o7planning.tutorial.rmi.Constants;
17
18 import org.o7planning.tutorial.rmi.WeatherData;
19
20
import org.o7planning.tutorial.rmi.WeatherService;
21
22
23
24
25 public class Client {
26
27
28
29
30 // Host or IP of Server
31
32 private static final String HOST = "localhost";
33
34
private static final int PORT = 1099;
35
36
37 private static Registry registry;
38
39
40
41
42
43 public static void main(String[] args) throws Exception {
.lookup(WeatherService.class.getSimpleName());
Constants.LOCATION_CHICAGO);
+ chicagoWeather.getWeather());
// Get Hanoi weather info:
Constants.LOCATION_HANOI);
Server.java
?
1
2 package org.o7planning.tutorial.rmi.server;
3
4
5
6
import java.rmi.AlreadyBoundException;
7
8
9 import java.rmi.Remote;
10
11 import java.rmi.RemoteException;
12
13
import java.rmi.registry.LocateRegistry;
14
15
16 import java.rmi.registry.Registry;
17
18
19
20
import org.o7planning.tutorial.rmi.WeatherService;
21
22
23
24
25 public class Server {
26
27
private static final int PORT = 1099;
28
29
30 private static Registry registry;
31
32
33
34
public static void startRegistry() throws RemoteException {
35
36
37
38
39 // Tạo một bộ đăng ký (Registry) tại Server.
40
41
registry = LocateRegistry.createRegistry(PORT);
// Client sẽ tìm trên bộ đăng ký với tên này để có thể gọi đối tượng.
registry.bind(name, remoteObj);
System.out.println("Server starting...");
startRegistry();
registerObject(WeatherService.class.getSimpleName(), new
WeatherServiceImpl());
System.out.println("Server started!");
Java cơ bản
Hướng dẫn lập trình Java Socket
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
1- Socket là gì?
í dụ Socket + Thread
3- V
4.3- InetAddress
1- Socket là gì?
Tại phía server (server-side):
● Thông thường, một chương trình server chạy trên một máy tính cụ thể, chương trình này có
một ổ cắm (Server Socket), ổ cắm được ràng buộc bởi cổng (Port number) cụ thể. Các chương
trình phục vụ (Server program) chỉ chờ đợi, lắng nghe tại ổ cắm (Server Socket) các Client để
thực hiện một yêu cầu kết nối.
● Các Client biết tên máy của máy tính mà trên đó chương trình chủ (server) đang chạy và số
cổng mà chương trình chủ lắng nghe. Để thực hiện một yêu cầu kết nối, Client cố gắng tạo ra
cuộc gặp với máy chủ trên máy tính của chương trình chủ và cổng. Các Client cũng cần phải
tự định danh chính nó với server để gắn với một cổng địa phương cái sẽ được sử dụng trong
suốt quá trình kết nối này, thông thường nó được gán bởi hệ điều hành.
Nếu mọi việc suôn sẻ, chương trình chủ (server program) chấp nhận kết nối của client. Khi chấp
nhận, máy chủ có được một socket mới bị ràng buộc vào cùng "cổng địa phương" và thông tin đầu
cuối (remote endpoint) của nó chính là địa chỉ và cổng của client. Nó đã tạo ra một socket mới để
chăm sóc Client vừa được chấp nhận kết nối, và tiếp tục lắng nghe tại ổ cắm gốc ban đầu
(ServerSocket) cho các yêu cầu kết nối khác.
Về phía Client, nếu kết nối được chấp nhận, một ổ cắm được tạo thành công và Client có thể sử
dụng ổ cắm để giao tiếp với chương trình chủ.
Các Client và Server có thể giao tiếp bằng cách ghi hay đọc từ ổ cắm (Socket) của chúng.
Dữ liệu ghi vào luồng đầu ra trên Socket của client sẽ nhận được trên luồng đầu vào của Socket tại
Server. Và ngược lại dữ liệu ghi vào luồng đầu ra trên Socket c ủa Server s ẽ nhận được trên luồng
đầu vào của Socket tại Client.
Định nghĩa:
Một Socket là một điểm cuối của một giao tiếp 2 chiều giữa hai chương trình chạy trên mạng. Socket
được giàng buộc với một cổng (con số cụ thể) để các tầng TCP (TCP Layer) có thể định danh ứng
dụng mà dữ liệu sẽ được gửi tới.
2- Ví dụ đơn giản với Socket
SimpleServerProgram.java
?
1
2 package org.o7planning.tutorial.socket;
3
4
5
6
import java.io.BufferedReader;
7
8
9 import java.io.BufferedWriter;
10
11 import java.io.IOException;
12
13
import java.io.InputStreamReader;
14
15
16 import java.io.OutputStreamWriter;
17
18 import java.net.ServerSocket;
19
20
import java.net.Socket;
21
22
23
24
25 public class SimpleServerProgram {
26
27
28
29
30 public static void main(String args[]) {
31
32
33
34
ServerSocket listener = null;
35
36
37 String line;
38
39 BufferedReader is;
40
41
42
43 BufferedWriter os;
44
45 Socket socketOfServer = null;
46
47
48
49
50
51
52
53
54
// Mở một ServerSocket tại cổng 9999.
55
56
57 // Chú ý bạn không thể chọn cổng nhỏ hơn 1023 nếu không là người dùng
58
59 // đặc quyền (privileged users (root)).
60
61
try {
62
63
64 listener = new ServerSocket(9999);
65
66 } catch (IOException e) {
67
68
System.out.println(e);
69
70
71 System.exit(1);
72
73 }
74
75
76
77
try {
// Đồng thời nhận được một đối tượng Socket tại server.
socketOfServer = listener.accept();
System.out.println("Accept a client!");
is = new BufferedReader(new
InputStreamReader(socketOfServer.getInputStream()));
os = new BufferedWriter(new
OutputStreamWriter(socketOfServer.getOutputStream()));
while (true) {
os.newLine();
// Đẩy dữ liệu đi
os.flush();
// Nếu người dùng gửi tới QUIT (Muốn kết thúc trò chuyện).
if (line.equals("QUIT")) {
os.write(">> OK");
os.newLine();
os.flush();
break;
}
}
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
System.out.println("Sever stopped!");
SimpleClientDemo.java
?
1
2 package org.o7planning.tutorial.socket;
3
4
5
6
import java.io.*;
7
8
9 import java.net.*;
10
11
12
13
public class SimpleClientDemo {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 // Địa chỉ máy chủ.
24
25 final String serverHost = "localhost";
26
27
28
29
30 Socket socketOfClient = null;
31
32 BufferedWriter os = null;
33
34
BufferedReader is = null;
35
36
37
38
39 try {
40
41
42
43 // Gửi yêu cầu kết nối tới Server đang lắng nghe
44
45 // trên máy 'localhost' cổng 9999.
46
47
socketOfClient = new Socket(serverHost, 9999);
48
49
50
51
52 // Tạo luồng đầu ra tại client (Gửi dữ liệu tới server)
53
54
os = new BufferedWriter(new
55
OutputStreamWriter(socketOfClient.getOutputStream()));
56
57
58
59
60 // Luồng đầu vào tại Client (Nhận dữ liệu từ server).
61
62
is = new BufferedReader(new
63
InputStreamReader(socketOfClient.getInputStream()));
64
65
66
67
68 } catch (UnknownHostException e) {
return;
} catch (IOException e) {
return;
}
try {
os.write("HELO");
os.newLine();
os.flush();
os.write("QUIT");
os.newLine();
os.flush();
// Bằng cách đọc luồng đầu vào của Socket tại Client.
String responseLine;
if (responseLine.indexOf("OK") != -1) {
break;
os.close();
is.close();
socketOfClient.close();
} catch (UnknownHostException e) {
} catch (IOException e) {
Chạy ví dụ:
Trước hết bạn cần chạy class SimpleServerProgram:
3- Ví dụ Socket + Thread
Thông thường một kết nối giữa chương trình chủ (Server) và 1 Client được tạo ra, bạn nên để chúng
nói chuyện với nhau trên một luồng (Thread), như vậy mỗi khi có một kết nối mới một luồng mới lại
được tạo ra.
ServerProgram.java
?
1
2 package org.o7planning.tutorial.socketthread;
3
4
5
6
import java.io.BufferedReader;
7
8
9 import java.io.BufferedWriter;
10
11 import java.io.IOException;
12
13
import java.io.InputStreamReader;
14
15
16 import java.io.OutputStreamWriter;
17
18 import java.net.ServerSocket;
19
20
import java.net.Socket;
21
22
23
24
25 public class ServerProgram {
26
27
28
29
30 public static void main(String args[]) throws IOException {
31
32
33
34
ServerSocket listener = null;
35
36
37
38
39 System.out.println("Server is waiting to accept user...");
40
41
42
43 int clientNumber = 0;
44
45
46
47
48
49
50 // Mở một ServerSocket tại cổng 7777.
51
52 // Chú ý bạn không thể chọn cổng nhỏ hơn 1023 nếu không là người dùng
53
54
// đặc quyền (privileged users (root)).
55
56
57 try {
58
59 listener = new ServerSocket(7777);
60
61
} catch (IOException e) {
62
63
64 System.out.println(e);
65
66 System.exit(1);
67
68
}
69
70
71
72
73 try {
74
75
while (true) {
76
77
78
79
80
81
82
83
84 // Chấp nhận một yêu cầu kết nối từ phía Client.
85
86 // Đồng thời nhận được một đối tượng Socket tại server.
87
88
89
90
91 Socket socketOfServer = listener.accept();
92
93 new ServiceThread(socketOfServer, clientNumber++).start();
94
95
}
96
97
98 } finally {
99
10 listener.close();
0
10
}
1
System.out.println(message);
this.clientNumber = clientNumber;
this.socketOfServer = socketOfServer;
// Log
@Override
try {
// Mở luồng vào ra trên Socket tại Server.
while (true) {
os.newLine();
// Đẩy dữ liệu đi
os.flush();
// Nếu người dùng gửi tới QUIT (Muốn kết thúc trò chuyện).
if (line.equals("QUIT")) {
os.write(">> OK");
os.newLine();
os.flush();
break;
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
ClientDemo.java
?
1
2 package org.o7planning.tutorial.socketthread;
3
4
5
6
import java.io.*;
7
8
9 import java.net.*;
10
11 import java.util.Date;
12
13
14
15
16 public class ClientDemo {
17
18
19
20
public static void main(String[] args) {
21
22
23
24
25 // Địa chỉ máy chủ.
26
27
final String serverHost = "localhost";
28
29
30
31
32 Socket socketOfClient = null;
33
34
BufferedWriter os = null;
35
36
37 BufferedReader is = null;
38
39
40
41
42
43 try {
44
45 // Gửi yêu cầu kết nối tới Server đang lắng nghe
46
47
// trên máy 'localhost' cổng 7777.
48
49
50 socketOfClient = new Socket(serverHost, 7777);
51
52
53
54
// Tạo luồng đầu ra tại client (Gửi dữ liệu tới server)
55
56
57 os = new BufferedWriter(new
58 OutputStreamWriter(socketOfClient.getOutputStream()));
59
60
61
62
// Luồng đầu vào tại Client (Nhận dữ liệu từ server).
63
64
65 is = new BufferedReader(new
66 InputStreamReader(socketOfClient.getInputStream()));
67
68
69
} catch (UnknownHostException e) {
return;
} catch (IOException e) {
return;
}
try {
os.newLine();
os.flush();
os.write("QUIT");
os.newLine();
os.flush();
// Bằng cách đọc luồng đầu vào của Socket tại Client.
String responseLine;
while ((responseLine = is.readLine()) != null) {
if (responseLine.indexOf("OK") != -1) {
break;
os.close();
is.close();
socketOfClient.close();
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
Contructor:
TT Phương thức và mô tả
Tạo một đối tượng Server Socket giàng buộc với một cổng cụ thể. Một ngoại lệ sẽ được ném
ra nếu cổng đó đã bị giàng buộc (Sử dung) bởi một chương trình khác.
Tương tự như cấu tử trên, tham số backlog định rõ có bao nhiêu client đến để lưu trữ trên
hàng đợi.
Tương tự như cấu tử trên, tham số InetAddress chỉ rõ địa chỉ IP địa phương sẽ được nối (bind)
tới. InetAddress được sử dụng cho các máy chủ có thể có nhiều địa chỉ IP, cho phép các máy
chủ để xác định các địa chỉ IP của nó để chấp nhận yêu cầu của client.
Tạo một Server Socket chưa định rõ cổng, địa chỉ. Khi sử dụng cấu tử này, sử dụng phương
thức bind(..) khi bạn sẵn sàng để nối với địa chỉ, cổng cụ thể.
Phương thức:
TT Phương thức và mô tả
1 public int getLocalPort()
Trả về cổng mà Server Socket đang lắng nghe. Phương thức này rất có ích, nếu bạn đưa vào
giá trị cổng bằng 0 trong cấu tử, nghĩa là nói với server tự tìm một cổng phù hợp, sau đó sử
dụng phương thức này để lấy ra giá trị thực.
Đợi một yêu cầu kết nối từ client. Phương thức này sẽ khóa ứng dụng cho tới khi có một yêu
cầu kết nối từ client đến trên cổng cụ thể hoặc hết thời gian chờ (Time-out), giả sử rằng thời
gian time-out được thiết lập sử dụng phương thức setSoTimeout(). Ngược lại method sẽ bị
khóa vô thời hạn.
Sét thời gian chờ tối đa (time-out) nghĩa là thời gian Server Socket sẽ chờ yêu cầu kết nối từ
người dùng trong quá trình accept().
Nối Server Socket tới một server cụ thể có cổng định sẵn trong đối tượng SocketAddress. Sử
dụng phương thức này nếu bạn khởi tạo ServerSocket sử dụng cấu tử mặc định (Không tham
số).
Constructor:
TT Cấu tử và mô tả
Cấu tử này tạo Socket kết nối tới Server cụ thể tại cổng xác định trong tham số, Nếu nó không
ném ra ngoại lệ, nghĩa là việc kết nối thành công, client đã kết nối với server.
2 public Socket(InetAddress host, int port) throws IOException
Cấu tử này giống hệt với các nhà xây dựng trước đó, ngoại trừ Server được biểu thị bằng một
đối tượng InetAddress.
3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
Kết nối tới host, port cụ thể, tạo ra một Socket trên host địa phương, và cổng địa phương được
chỉ định trong tham số.
4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.
Cấu tử này giống hệt với cấu tử trên, ngoại trừ server được biểu thị bằng một đối tượng
InetAddress thay vì một String
5 public Socket()
Tạo một Socket chưa kết nối. Sử dụng phương thức connect() để kết nối socket này tới server.
Phương thức:
TT Phương thức và mô tả
Phương thức này kết nối socket này tới host chỉ định. Phương thức này cần thiết chỉ khi bạn
khởi tạo một đối tượng Socket thông qua cấu tử mặc định (Không tham số).
Phương thức này trả về địa chỉ của máy tính mà socket này kết nối tới.
3 public int getPort()
Trả về luồng đầu vào của Socket. Luồng đầu vào này được kết nối với luồng đầu ra của Socket
từ xa (remote socket).
Trả về luồng đầu ra của Socket. Luồng đầu ra này kết nối với luồng đầu vào của Socket từ xa.
Đóng socket, nghĩa là làm cho Socket này không còn khả năng trò chuyện với máy kia.
4.3- InetAddress
Phương thức:
TT Phương thức và mô tả
Trả về đối tượng InetAddress dựa trên tên máy chủ được cung cấp và địa chỉ IP.
Xác định địa chỉ IP của host, cho bởi tên host.
4 String getHostAddress()
5 String getHostName()
7 String toString()
Java cơ bản
Các nền tảng nào bạn nên chọn để lập trình ứng dụng Java Desktop?
Eclipse Org
Eclipse RCP
Eclipse RAP
Java cơ bản
Công nghệ của Eclipse
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
iới thiệu
1- G
2.1- Swing
1- Giới thiệu
Thực tế có một số câu hỏi thông dụng với Java:
● Tôi nên chọn giải pháp nào để lập trình một ứng dụng Desktop
● Có một giải pháp nào để lập trình một website có giao diện giống ứng dụng Desktop không?
Trong tài liệu này tôi sẽ trả lời tổng quan về câu hỏi trên đồng thời có các giải pháp giúp bạn làm
được điều đó.
Đây là một ứng dụng Desktop viết bằng Java ( Java Swing):
Và đây là một ứng dụng Web có giao diện giống giao diện một ứng dụng Desktop, nó được viết trên
Eclipse RAP:
● http://rap.eclipsesource.com/demo/release/workbench/
2- Lập trình Java ứng dụng Desktop
Thực tế để lập trình ứng dụng Desktop bạn có 2 lựa chọn
● Sử dụng Swing - Là một thư viện tích hợp sẵn trên JDK và có khả năng chạy trên mọi hệ điều
hành khác nhau (Windows, Unix, Mac OS,..)
● Sử dụng SWT - Là một thư viện để lập trình ứng dụng Desktop được phát triển bởi IBM. Nó
có khả năng chạy trên mọi hệ điều hành khác nhau (Window, Unix, Mac OS,..)
Đây là hình ảnh một ứng dụng Desktop v iết bằng SWT v à chạy trên các hệ điều hành khác nhau:
Đây là hình ảnh ứng dụng Desktop viết bằng S wing. Với "Look And Feel" mặc định trông nó khá
ngô nghê. Trong lập trình bạn có thể chọn một L -A-F khác để có được giao diện giống với Windows
ếu muốn.
hoặc Linux n
2.1- Swing
AWT (Abstract Window Toolkit) - là một bộ thư viện được phát triển dành cho lập trình Desktop có
sẵn trong JDK, tuy nhiên đáng tiếc là nó hoạt động không như mong muốn trên các hệ điều hành
khác nhau. Đó là lý do Swing được ra đời thay thế cho AWT, để đảm bảo rằng nó chạy tốt trên các
hệ điều hành khác nhau.
Swing xây dựng giao diện đồ họa hoàn toàn bằng Java. Và chạy trên mọi hệ điều hành. Nó không
thay thế AWT mà thừa kế từ AWT, đây là một điểm yếu của nó là bối rối những người lập trình, một
số lượng lớn các lớp thuộc AWT g iờ đã không còn được dùng nữa, hoặc nó lại là lớp để các lớp của
Swing t hừa kế. Theo tôi chính điều này làm Swing b ị đánh giá thấp.
SWT (Standard Widget Toolkit) là một thư viện lập trình ứng dụng Desktop đ ược phát triển bởi
IBM. Nó không phát triển đồ họa hoàn toàn bằng Java. Khi chạy trên hệ điều hành nào, nó cố gắng
tận dụng các giao diện đồ họa của hệ điều hành đó ( Button, Label, ...) và chỉ tạo đồ họa thành phần
mà hệ điều hành đó không có bằng Java.
Swing là một thư viện thuần Java, khi bạn lập trình xong ứng dụng bạn có thể sét đặt Look And Feel
(Nhìn và cảm nhận) để có một giao diện giống của Windows, hoặc Linux h oặc Mac Os,... Có sẵn
một số Look And Feel trên JDK b ạn có thể sử dụng hoặc có thể mua các L-A-F. Như vậy bạn có
chạy một ứng dụng Swing trên hệ điều hành Windows mà giao diện hiển thị lên lại là của Linux, Mac
Os, ..
Đây là một link giới thiệu về các L-A-F đẹp:
● http://www.jwrapper.com/blog/6-great-look-and-feels-to-make-your-java-app-pretty
SWT - Đây là một thư viện không viết hoàn toàn bằng Java. Khi nó chạy trên hệ điều hành nào nó cố
gắng tận dụng các thư viện thành phần của hệ điều hành đó (chẳng hạn tận dụng các Button, Label,
Frame, ...), và chỉ dùng Java đ
ể vẽ các thành phần nếu nó không có trên hệ điều hành. Như vậy về
tốc độ SWT nhanh hơn Swing.
Với SWT chúng ta không có khái niệm Look And Feel như Swing. Khi bạn chạy ứng dụng trên nền
hệ điều hành nào, giao diện sẽ mang đặc tính của hệ điều hành đó.
Tôi nghĩ rằng bạn nên chọn SWT cho việc lập trình ứng dụng Desktop vì đây là một bộ thư viện
phong phú các thành phần giao diện khác nhau. Hơn nữa nó là bộ thư viện ra đời sau Swing, nó học
hỏi và giải quyết các yếu điểm của Swing.
SWT với các bộ thư viện mở rộng đang được phát triển thêm, chẳng hạn như:
● Nebula
Eclipse phát triển một nền tảng mới gọi là RAP (Remote Application Platform) - RAP cho phép bạn
lập trình các ứng dụng có giao diện giống các ứng dụng Desktop, và lại sử dụng các class quen
thuộc có trong SWT. Như vậy bạn có thể viết một ứng dụng mà có thể chạy cả trên nền Web và chạy
cả trên nền Desktop. Đây là một điểm mạnh nếu bạn chọn SWT.
Hãy xem một Demo ( bản giới thiệu) chương trình viết bằng RAP:
● http://eclipse.org/rap/demos/
3- Công nghệ của Eclipse
Chúng ta cần có một cái nhìn về công nghệ của Eclipse
RCP (Rich Client Platform) : Là một platform s ử dụng thư viện SWT để lập trình các ứng dụng
Desktop. Có thể chạy trên mọi hệ điều hành khác nhau.
RAP (Remote Application Platform): Là một Platform sử dụng thư viện RWT để lập trình các ứng
dụng chạy trên Web giống ứng dụng Desktop.
● RWT (RAP Widget Toolkit) là bộ thư viện với các class cùng tên với class của SWT, và có
các method tương tự, giúp bạn lập trình các ứng dụng RAP c hạy trên Web. Chính vì đặc tính
này chỉ cần 1 source code, bạn có thể chạy ứng dụng trên nền Desktop hoặc trên nền Web.
Như vậy RCP là một Platform sử dụng SWT làm cơ sở để xây dựng lên. Bạn có thể sử dụng Platform
ể lập trình lên ứng dụng Desktop.
RCP đ
Hình minh họa dưới đây là một ứng dụng đơn giản (Chỉ dùng tới SWT, chưa dùng gì tới những thứ
cao cấp của RCP Platform):
RCP Platform đã xây dựng một nền tảng cho phép bạn lập trình ra các giao diện có cấu trúc phức
tạp giống Eclipse IDE, nó bao gồm các hệ thống Menu, Toolbar, View, Editor, ...
RCP c ũng cho phép bạn phát triển các Plugin tích hợp vào Eclipse mà bạn đang sử dụng.
5- RAP làm được những gì?
RAP (Remote Application Platform): Là một Platform sử dụng thư viện RWT để lập trình các ứng
iống ứng dụng Desktop.
dụng chạy trên Web g
● RWT (RAP Widget Toolkit) là bộ thư viện với các class cùng tên với class của SWT, và có
các method tương tự, giúp bạn lập trình các ứng dụng RAP c hạy trên Web. Chính vì đặc tính
này chỉ cần 1 source code, bạn có thể chạy ứng dụng như một ứng dụng Desktop hoặc trên
Web.
Cũng giống như RCP, RAP là một Platform, nó cũng cho phép tạo ra các ứng dụng có giao diện phức
tạp giống Eclipse IDE.
6- RAP & RCP - Tại sao code rất giống nhau?
Đây là cấu trúc 2 Platform:
1
2 import org.eclipse.swt.widgets.Display;
3
4 import org.eclipse.swt.widgets.Shell;
5
6
import org.eclipse.swt.layout.FillLayout;
7
8
9 import org.eclipse.swt.SWT;
10
11 import org.eclipse.swt.widgets.Composite;
12
13
import org.eclipse.swt.layout.GridLayout;
14
15
16 import org.eclipse.swt.widgets.Button;
17
18
19
20
public class MyApplicationWindow {
21
22
23
.......
.......
btnMyButton.setText("My Button");
Code của lớp Button trong SWT (chạy trên desktop) rõ ràng khác với code class Button c ủa RWT
(vốn để chạy trên WEB).
● Class Button c ủa SWT được đóng gói trong file jar có tên org.eclipse.swt_*.jar
● Class B utton c ủa RWT đ
ược đóng gói trong file jar có tên org.eclipse.rap.rwt_*.jar
Target Platform là một môi trường thư viện, bạn có thể khai báo.
Bạn có thể khai báo ra 2 Target Platform. Một cái gồm các thư viện RCP, và một cái gồm các thư
viện RAP.
Cùng một code bạn chạy với RCP Target Platform sẽ là một ứng dụng Desktop. Khi chạy với RAP
Target Platform sẽ là một ứng dụng chạy trên Web.
Tất nhiên RAP và RCP có đôi chút khác biệt, không phải tất cả các thành phần của SWT đ ều có
tương ứng trên RWT, và ngược lại. Tùy trường hợp có thể sử lý các khác biệt này. Các ứng dụng có
thể chạy trên trên cả nền Desktop và Web được biết tới với khái niệm "Single Sourcing".
Làm việc với SWT nghĩa là làm việc với các đối tượng Widget ( Button, Label, ..) và xử lý Layout.
WindowBuilder là một plugin cho phép kéo thả các thành phần lên giao diện, và tự động tạo ra code
tương ứng.
Bạn có thể tham khảo tài liệu dưới đây, nó hướng dẫn lập trình SWT v ới WindowBuilder là công cụ
trực quan, dễ dàng kéo thả các thành phần giao diện.
SWT:
● Hướng dẫn lập trình Java Desktop sử dụng SWT
RCP
● Hướng dẫn lập trình Eclipse RCP 4 cho người mới bắt đầu - Ứng dụng e4 Workbench
RAP
● Hướng dẫn lập trình Eclipse RAP cho người mới bắt đầu - Ứng dụng cơ bản
Eclipse Org
Eclipse RCP
Eclipse RAP
Java cơ bản
Công nghệ của Eclipse
Mục lục
1- Giới thiệu
2- Thư viện
3- Tạo project
4- IOUtils
5- FileUtils
6- FilenameUtils
7- FileSystemUtils
8- Line iterator
Apache Org
Java cơ bản
Apache Org
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
iới thiệu
1- G
hư viện
2- T
ạo project
3- T
4- IOUtils
5- FileUtils
6- FilenameUtils
7- FileSystemUtils
8- Line iterator
1- Giới thiệu
2- Thư viện
● http://mvnrepository.com/artifact/commons-io/commons-io
3- Tạo project
Tạo một Maven Project.
● Group ID: org.o7planning
● Artifact ID: CommonsIOTutorial
Đây là hình ảnh project được tạo ra.
1
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
5 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
6 http://maven.apache.org/xsd/maven-4.0.0.xsd">
7
8
<modelVersion>4.0.0</modelVersion>
9
10
11 <groupId>org.o7planning</groupId>
12
13 <artifactId>CommonsIOTutorial</artifactId>
14
15
<version>0.0.1-SNAPSHOT</version>
16
17
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
</project>
4- IOUtils
IOUtils là một class tiện ích hỗ trợ để xử lý vào ra dữ liệu một cách nhanh chóng hơn. Nếu bạn sử
dụng java.io chuẩn của java bạn có thể làm được những thứ mình muốn. Nhưng muốn viết code
nhanh hơn, tiết kiệm thời gian hơn, hãy sử dụng IOUtils.
● http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/I
OUtils.html
Hãy xem một đoạn code được xử lý theo cách thông thường (Dùng những gì có sẵn trong JDK).
1
2 InputStream in = new URL("http://commons.apache.org").openStream();
3
4 try {
5
6
InputStreamReader inR = new InputStreamReader(in);
7
8
9 BufferedReader buf = new BufferedReader(inR);
10
11 String line;
System.out.println(line);
} finally {
in.close();
1
2 InputStream in = new URL("http://commons.apache.org").openStream();
3
4 try {
5
6
System.out.println(IOUtils.toString(in));
} finally {
IOUtils.closeQuietly(in);
Nhìn vào 2 đoạn code trên chúng ta thấy rõ ràng cùng làm một mục tiêu, nhưng sử dụng IOUtils ngắn
gọn hơn hẳn.
ReadURL1.java
?
1
2 package org.o7planning.tutorial.commonsio.io;
3
4
5
6
import java.io.BufferedReader;
7
8
9 import java.io.IOException;
10
11 import java.io.InputStream;
12
13
import java.io.InputStreamReader;
14
15
16 import java.net.MalformedURLException;
17
18 import java.net.URL;
19
20
21
22
23 public class ReadURL1 {
24
25
26
27
public static void readURL() throws MalformedURLException, IOException {
28
29
30 InputStream in = new URL("http://commons.apache.org").openStream();
31
32 try {
33
34
InputStreamReader inR = new InputStreamReader(in);
String line;
while ((line = buf.readLine()) != null) {
System.out.println(line);
} finally {
in.close();
try {
readURL();
} catch (Exception e) {
e.printStackTrace();
ReadURL2.java
?
1
2 package org.o7planning.tutorial.commonsio.io;
3
4
5
6
import java.io.IOException;
7
8
9 import java.io.InputStream;
10
11 import java.net.MalformedURLException;
12
13
import java.net.URL;
14
15
16
17
18 import org.apache.commons.io.IOUtils;
19
20
21
22
23 public class ReadURL2 {
24
25
26
27
public static void readURL() throws MalformedURLException, IOException {
28
29
InputStream in = new URL("http://commons.apache.org").openStream();
try {
System.out.println(IOUtils.toString(in));
} finally {
IOUtils.closeQuietly(in);
}
try {
readURL();
} catch (Exception e) {
e.printStackTrace();
5- FileUtils
Class FileUtils chứa các method tiện ích để làm việc với các đối tượng File. Bao gồm đọc, viết, copy,
và so sánh các file.
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
FileUtilsReadFile.java
?
1
2 package org.o7planning.tutorial.commonsio.fileutils;
3
4
5
6
7
8
9 import java.io.File;
10
11 import java.io.IOException;
12
13
import java.util.List;
14
15
16
17
18 import org.apache.commons.io.FileUtils;
19
20
21
22
23 public class FileUtilsReadFile {
24
25
26
27
28
29
30 public static void readFile() throws IOException {
for(String s: lines) {
System.out.println(s);
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
FileUtilsTouchFile.java
?
1
2 package org.o7planning.tutorial.commonsio.fileutils;
3
4
5
6
import java.io.IOException;
7
8
9 import org.apache.commons.io.FileUtils;
10
11 import java.io.File;
12
13
14
15
16 public class FileUtilsTouchFile {
17
18
19
20
public static void main(String[] args) {
21
22
23
24
25 try {
26
27
// E:/test.txt chưa có trên hệ thống.
28
29
30 File testFile = new File("E:/test.txt");
31
32
33
// Và thay đổi thời gian sửa lần cuối của file bằng thời gian hiện tại.
FileUtils.touch(testFile);
+ testFile.lastModified());
ex.printStackTrace();
Chạy lần đầu tiên (Lúc E:/test.txt thực sự chưa tồn tại trên ổ cứng)
Chạy lần thứ 2 (Khi E:/test.txt đã được tạo ra và được sét đặt thời gian sửa đổi lần cuối trước đó)
Sử dụng FileUtils cho phép bạn dễ dàng copy và paste file từ nơi nọ sang nơi kia, hoặc copy các file
từ thư mục nọ sang thư mục kia.
FileUtilsCopyDirectory.java
?
1
2 package org.o7planning.tutorial.commonsio.fileutils;
3
4
5
6
import java.io.File;
7
8
9 import java.io.IOException;
10
11
12
13
import org.apache.commons.io.FileUtils;
14
15
16
17
18 public class FileUtilsCopyDirectory {
19
20
try {
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
}
6- FilenameUtils
Class FilenameUtils có các method hữu ích để làm việc với tên tập tin mà không sử dụng các đối
tượng File. Class này nhằm mục đích phù hợp ở giữa Unix và Windows, để hỗ trợ quá trình chuyển
đổi giữa các môi trường tổng hợp (chẳng hạn như di chuyển từ môi trường lập trình phát triển sang
môi trường sản phẩm hoàn chỉnh).
FilenameUtils javadoc:
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FilenameUtils.
html
FilenameUtilsNormalize.java
?
1
2 package org.o7planning.tutorial.commonsio.filenameutils;
3
4
5
6
import org.apache.commons.io.FilenameUtils;
7
8
9
10
11 public class FilenameUtilsNormalize {
12
13
14
System.out.println(normalized);
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FilenameUtils.
html
7- FileSystemUtils
Class FileSystemUtils có các method hữu ích để làm việc với hệ thống tập tin để truy cập vào các
chức năng không được hỗ trợ bởi JDK. Hiện tại, class này mới chỉ có các method để có được không
gian trống trên ổ đĩa. Chú ý là nó sử dụng các lệnh command line. Không sử dụng mã tự nhiên
(native code).
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileSystemUtil
s.html
FileSystemUtilsFreeSpaceKb.java
?
1
2 package org.o7planning.tutorial.commonsio.filesystemutils;
3
4
5
6
import java.io.IOException;
7
8
9
10
11 import org.apache.commons.io.FileSystemUtils;
12
13
14
15
16 public class FileSystemUtilsFreeSpaceKb {
17
public static void main(String[] args) {
try {
Long kb = FileSystemUtils.freeSpaceKb("C:/");
} catch (IOException e) {
e.printStackTrace();
8- Line iterator
Class org.apache.commons.io.LineIterator Cung cấp một cách linh hoạt để làm việc với một tập tin
dựa trên dòng. Một ví dụ có thể được tạo ra trực tiếp, hoặc thông qua các method của FileUtils hoặc
IOUtils. Bạn nên sử dụng theo cách:
1
2 LineIterator it = FileUtils.lineIterator(file, "UTF-8");
3
4 try {
5
6
while (it.hasNext()) {
7
8
9 String line = it.nextLine();
} finally {
LineIterator.closeQuietly(it);
LineIteratorExample.java
?
1
2 package org.o7planning.tutorial.commonsio.lineiterator;
3
4
5
6
import java.io.File;
7
8
9 import java.io.IOException;
10
11
12
13
import org.apache.commons.io.FileUtils;
14
15
16 import org.apache.commons.io.LineIterator;
17
18
19
20
public class LineIteratorExample {
21
22
23 public static void main(String[] args) {
24
25 try {
26
27
File file = new File("D:/test.txt");
28
29
30 LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
//
if (line != null && line.startsWith("##")) {
System.out.println(line.substring(2));
} finally {
LineIterator.closeQuietly(it);
} catch (IOException e) {
e.printStackTrace();
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/filefilter/packa
ge-summary.html
Ví dụ, java.io.FileFilter có thể được dùng để bạn lọc lấy ra các File theo ý bạn trong 1 thư mục nào
đó. Nhưng sẽ là tốt hơn nếu bạn sử dụng các lớp có trong package
org.apache.commons.io.filefilter. Nó có nhiều cái viết sẵn cho bạn, và chỉ cần sử dụng.
FileFilterExample1.java
?
1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileFilter;
10
11
12
13
public class FileFilterExample1 {
14
15
16
17
18 public static void main(String[] args) {
19
20
21
22
23 FileFilter filter = new MyFileFilter();
24
25
26
27
File dir = new File("C:/test");
28
29
30
31
32 // Lấy ra danh sách file có phần mở rộng js hoặc css
33
34
File[] list = dir.listFiles(filter);
35
if (abstractPath.endsWith(".js") || abstractPath.endsWith(".css")) {
return true;
return false;
}
}
HiddenFileFilterExample.java
1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9
10
11 import org.apache.commons.io.filefilter.HiddenFileFilter;
12
13
14
15
16 public class HiddenFileFilterExample {
17
System.out.println(files[i]);
}
}
FileFilterExample2.java
1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileFilter;
10
11
12
13
import org.apache.commons.io.filefilter.SuffixFileFilter;
14
15
16
17
18 public class FileFilterExample2 {
19
20
21
22
23 public static void main(String[] args) {
CombineTwoFilterExample.java
?
1
2 package org.o7planning.tutorial.commonsio.filefilter;
3
4
5
6
import java.io.File;
7
8
9 import java.io.FileFilter;
10
11
12
13
import org.apache.commons.io.filefilter.FileFilterUtils;
14
15
16 import org.apache.commons.io.filefilter.HiddenFileFilter;
17
18 import org.apache.commons.io.filefilter.IOFileFilter;
19
20
import org.apache.commons.io.filefilter.SuffixFileFilter;
21
22
23
24
25 public class CombineTwoFilterExample {
26
27
28
29
30 public static void main(String[] args) {
31
32
33
34
String[] suffixs = new String[] { ".js", ".css" };
//
IOFileFilter filter2 = HiddenFileFilter.VISIBLE;
//
// Bộ lọc mới chấp nhận các file có đuôi js, css và phải là file không ẩn.
.andFileFilter(filter1, filter2);
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/comparator/p
ackage-summary.html
SizeFileComparatorExample.java
?
1
2 package org.o7planning.tutorial.commonsio.comparator;
3
4
5
6
import java.io.File;
7
8
9 import java.io.IOException;
10
11 import java.util.Arrays;
12
13
14
15
16 import org.apache.commons.io.FileUtils;
17
18 import org.apache.commons.io.comparator.SizeFileComparator;
19
20
21
22
23 public class SizeFileComparatorExample {
24
25
26
27
public static void main(String[] args) throws IOException {
28
29
30 // Thư mục hiện tại (Thư mục của project)
31
32 File directory = new File(".");
33
34
File[] files = directory.listFiles();
35
36
37
38
39 System.out.println("Sap xep mac dinh");
40
41
42
43 displayFiles(files);
44
45
46
47
Arrays.sort(files, SizeFileComparator.SIZE_COMPARATOR);
48
49
50 System.out
51
52 .println("\nSizeFileComparator.SIZE_COMPARATOR (Tang dan, thu muc coi
53 nhu kich thuoc bang 0)");
54
55
displayFiles(files);
56
57
58
59
60 Arrays.sort(files, SizeFileComparator.SIZE_REVERSE);
System.out
displayFiles(files);
Arrays.sort(files, SizeFileComparator.SIZE_SUMDIR_COMPARATOR);
System.out
displayFilesWithDirectorySizes(files);
Arrays.sort(files, SizeFileComparator.SIZE_SUMDIR_REVERSE);
System.out
displayFilesWithDirectorySizes(files);
file.getName());
if (file.isDirectory()) {
System.out.printf(
file.getName());
} else {
file.getName());
1
2 Sap xep mac dinh
3
4 .classpath Size:1431
5
6
.project Size:569
7
8
9 .settings Size:4096
10
11 pom.xml Size:547
12
13
src Size:0
14
15
16 target Size:0
17
18 test.txt Size:0
19
20
21
22
23 SizeFileComparator.SIZE_COMPARATOR (Tang dan, thu muc coi nhu kich thuoc
24 bang 0)
25
26 .settings Size:4096
27
28
src Size:0
29
30
31 target Size:0
32
33 test.txt Size:0
34
35
pom.xml Size:547
36
37
38 .project Size:569
39
40
41 .classpath Size:1431
42
43
44
45
SizeFileComparator.SIZE_REVERSE (Giam dan, thu muc coi nhu kich thuoc bang 0)
.classpath Size:1431
.project Size:569
pom.xml Size:547
.settings Size:4096
src Size:0
target Size:0
test.txt Size:0
test.txt Size:0
.settings Size:489
pom.xml Size:547
.project Size:569
.classpath Size:1431
src Size:11611
target Size:22459
target Size:22459
src Size:11611
.classpath Size:1431
.project Size:569
pom.xml Size:547
.settings Size:489
test.txt Size:0
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/package
-summary.html
● http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/output/packag
e-summary.html
Apache Org
Java cơ bản
Mục lục
1- Giới thiệu
2- Thư viện
3- Tạo Project
Apache Org
Java cơ bản
Apache Org
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
iới thiệu
1- G
hư viện
2- T
ạo Project
3- T
4- Chú ý cho Gmail
1- Giới thiệu
Commons Email là một thư viện Java của Apache liên quan tới Email. Trong thực tế để làm việc với
Java Email bạn có thể sử dụng JavaMail API đã được tích hợp sẵn trong JDK6. Commons Email
đơn giản chỉ là giúp bạn làm việc với JavaMail API dễ dàng hơn, nó không thay thế cho JavaMail
API.
Cũng giống như Commons IO không thay thế cho J avaIO mà chỉ bao gồm nhiều class, method tiện
ích để bạn làm việc với Java IO dễ dàng hơn, tiết kiệm thời gian code cho bạn.
2- Thư viện
● http://mvnrepository.com/artifact/org.apache.commons/commons-email
Maven:
** pom.xml **
1
2 <!-- http://mvnrepository.com/artifact/org.apache.commons/commons-email -->
3
4
5
6
<dependency>
7
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.2</version>
</dependency>
Xem thêm:
3- Tạo Project
Tạo một Maven Project dùng cho việc test các ví dụ trong tài liệu này. Bạn có thể tạo một Project
thông thường, sau đó download thư viện và khai báo vị trí của chúng theo cách thông thường.
Nếu bạn sử dụng Commons Email trong một project thông thường, bạn cần download các thư viện
cần thiết, bạn có thể xem ở phụ lục ở cuối tài liệu.
Đây là hình ảnh Project được tạo ra.
pom.xml
?
1
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
6
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
7
8
9 http://maven.apache.org/xsd/maven-4.0.0.xsd">
10
11
12
13
<modelVersion>4.0.0</modelVersion>
14
15
16 <groupId>org.o7planning</groupId>
17
18 <artifactId>CommonsEmailTutorial</artifactId>
19
20
<version>0.0.1-SNAPSHOT</version>
21
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
Trên trình duyệt đăng nhập vào Gmail c ủa ban, và truy cập đường dẫn sau:
● https://www.google.com/settings/security/lesssecureapps
Một số ứng dụng và thiết bị sử dụng công nghệ đăng nhập ít bảo mật hơn, làm cho tài khoản của
bạn dễ bị tổn thương hơn. Bạn có thể tắt quyền ( T urn Off) truy cập cho các ứng dụng này mà
chúng tôi đề xuất hoặc bật quyền ( Turn On) truy cập nếu bạn muốn sử dụng chúng bất chấp rủi ro.
5- Ví dụ gửi email đơn giản
Trước hết là một ví dụ gửi một Email đơn giản với Commons-Email
Constants.java
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
public class Constants {
7
8
9
10
11
SimpleTextEmail.java
?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import org.apache.commons.mail.DefaultAuthenticator;
7
8
9 import org.apache.commons.mail.Email;
10
11 import org.apache.commons.mail.SimpleEmail;
12
13
14
15
16 public class SimpleTextEmail {
17
18
19
20
public static void main(String[] args) {
21
22
23 try {
24
25 Email email = new SimpleEmail();
26
27
28
29
30 // Cấu hình thông tin Email Server
31
32 email.setHostName("smtp.googlemail.com");
33
34
email.setSmtpPort(465);
35
36
37 email.setAuthenticator(new DefaultAuthenticator(Constants.MY_EMAIL,
38
39 Constants.MY_PASSWORD));
// Với gmail cái này là bắt buộc.
email.setSSLOnConnect(true);
// Người gửi
email.setFrom(Constants.MY_EMAIL);
// Tiêu đề
email.setSubject("Test Email");
// Người nhận
email.addTo(Constants.FRIEND_EMAIL);
email.send();
System.out.println("Sent!!");
} catch (Exception e) {
e.printStackTrace();
EmailWithAttachment.java
?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import org.apache.commons.mail.DefaultAuthenticator;
7
8
9 import org.apache.commons.mail.EmailAttachment;
10
11 import org.apache.commons.mail.MultiPartEmail;
12
13
14
15
16 public class EmailWithAttachment {
17
18
19
20
public static void main(String[] args) {
21
22
23 try {
24
25 // Tạo một đối tượng đính kèm
26
27
EmailAttachment attachment = new EmailAttachment();
28
29
30 attachment.setPath("C:/mypictures/map-vietnam.png");
31
32 attachment.setDisposition(EmailAttachment.ATTACHMENT);
33
34
attachment.setDescription("Vietnam Map");
35
36
37 attachment.setName("Map");
38
39
40
41
42
43 // Tạo đối tượng Email
44
45 MultiPartEmail email = new MultiPartEmail();
46
// Cấu hình
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setSSLOnConnect(true);
email.setAuthenticator(new DefaultAuthenticator(Constants.MY_EMAIL,
Constants.MY_PASSWORD));
email.setFrom(Constants.MY_EMAIL, "TRAN");
email.addTo(Constants.FRIEND_EMAIL, "Hong");
email.setSubject("The Map");
// Gửi email
email.send();
System.out.println("Sent!");
} catch (Exception e) {
e.printStackTrace();
Kết quả:
Một ví dụ khác gửi Email có đính kèm file từ một liên kết (Link)
EmailWithAttachment2.java
?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import java.net.URL;
7
8
9
10
11 import org.apache.commons.mail.DefaultAuthenticator;
12
13
import org.apache.commons.mail.EmailAttachment;
14
15
16 import org.apache.commons.mail.MultiPartEmail;
17
18
19
20
public class EmailWithAttachment2 {
21
22
23
24
25 public static void main(String[] args) {
26
27
try {
28
29
30 // Tạo đối tượng đính kèm
31
32 EmailAttachment attachment = new EmailAttachment();
33
34
attachment.setURL(new URL(
35
36
37 "http://www.apache.org/images/asf_logo_wide.gif"));
38
39 attachment.setDisposition(EmailAttachment.ATTACHMENT);
40
41
42
43 attachment.setDescription("Apache logo");
44
45 attachment.setName("Apache logo");
46
47
48
49
// Tạo đối tượng email
// Cấu hình
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setSSLOnConnect(true);
email.setAuthenticator(new DefaultAuthenticator(
Constants.MY_EMAIL, Constants.MY_PASSWORD));
email.setFrom(Constants.MY_EMAIL, "TRAN");
email.addTo(Constants.FRIEND_EMAIL, "Hong");
email.setSubject("The logo");
email.attach(attachment);
// Gửi email
email.send();
System.out.println("Sent!");
} catch (Exception e) {
e.printStackTrace();
SendHtmlEmail.java
?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import java.net.URL;
7
8
9
10
11 import org.apache.commons.mail.DefaultAuthenticator;
12
13
import org.apache.commons.mail.HtmlEmail;
14
15
16
17
18 public class SendHtmlEmail {
19
20
21
22
23 public static void main(String[] args) {
24
25 try {
26
27
// Tạo đối tượng Email
28
29
30 HtmlEmail email = new HtmlEmail();
31
32
33
34
35
36
37 // Cấu hình
38
39 email.setHostName("smtp.googlemail.com");
40
41
42
43 email.setSmtpPort(465);
44
45 email.setAuthenticator(new DefaultAuthenticator(
46
47
Constants.MY_EMAIL,Constants.MY_PASSWORD));
48
49
50 email.setSSLOnConnect(true);
51
52 email.setFrom(Constants.MY_EMAIL, "TRAN");
// Người nhận
email.addTo(Constants.FRIEND_EMAIL);
// Tiêu đề
+ cid + "\"></html>");
// (Trong trường hợp chương trình đọc mail của người nhận ko hỗ trợ đọc
HTML Email)
// Gửi email
email.send();
System.out.println("Sent!!");
} catch (Exception e) {
e.printStackTrace();
}
}
SendHtmlEmbedImageEmail.java
?
1
2 package org.o7planning.tutorial.commonsemail;
3
4
5
6
import java.net.URL;
7
8
9
10
11 import org.apache.commons.mail.DefaultAuthenticator;
12
13
import org.apache.commons.mail.ImageHtmlEmail;
14
15
16 import org.apache.commons.mail.resolver.DataSourceUrlResolver;
17
18
19
20
public class SendHtmlEmbedImageEmail {
21
22
23 public static void main(String[] args) {
24
25 try {
26
27
// Mẫu nội dung Email gửi đi.
28
29
30 // Ở đây Img có đường dẫn tương đối (**)
31
32 String htmlEmailTemplate = "<h2>Hello!</h2>"
33
34
+"This is Apache Logo <br/>"
35
36
37 +"<img src='proper/commons-email/images/commons-logo.png'/>";
38
39
40
41
42
43 // Tạo đối tượng Email.
44
45 ImageHtmlEmail email = new ImageHtmlEmail();
46
47
48
49
50
51
52 // Cấu hình
53
54
email.setHostName("smtp.googlemail.com");
55
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(
Constants.MY_EMAIL, Constants.MY_PASSWORD));
email.setSSLOnConnect(true);
email.setFrom(Constants.MY_EMAIL, "TRAN");
email.addTo(Constants.FRIEND_EMAIL);
// Định nghĩa URL cơ sở để xác định đúng vị trí nguồn dữ liệu (img,..)
// (Trong trường hợp nó có đường dẫn tương đối, ví dụ Img trên)
email.setDataSourceResolver(new DataSourceUrlResolver(url) );
email.setHtmlMsg(htmlEmailTemplate);
// (Trong trường hợp chương trình đọc email của người nhận ko hỗ trợ HTML).
// Gửi email
email.send();
System.out.println("Sent!!");
} catch (Exception e) {
e.printStackTrace();
● http://mvnrepository.com/artifact/org.apache.commons/commons-email
Tiếp theo download thư viện Email API:
● http://mvnrepository.com/artifact/com.sun.mail/javax.mail
Cuối cùng, bạn download được 2 file jar.
hư viện (Library)
3.1- T
ạo project
3.2- T
Apache Org
Java cơ bản
Apache Org
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
● Log4J Logger
● Jdk14 Logger
● Simple Logger
Commons Logging là một thư viện cho phép bạn làm việc với một trong 3 bộ thư viện trên một cách
dễ dàng hơn. Như vậy để viết một chương trình Log, một mình nó không thể là một Logger. Một
cách tương tự bạn làm việc với java.io để sử lý vào ra dữ liệu, Commons IO là bộ thư viện viết dựa
trên java.io giúp bạn sử lý IO dễ dàng hơn, Common IO không thể thay thế java.io.
● http://mvnrepository.com/artifact/commons-logging/commons-logging
Maven:
1
2 <dependency>
3
4
<groupId>commons-logging</groupId>
5
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
1
2 <dependency>
3
4
<groupId>log4j</groupId>
5
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
?
1
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3
4
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
6
7 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
8 http://maven.apache.org/xsd/maven-4.0.0.xsd">
9
10
<modelVersion>4.0.0</modelVersion>
11
12
13 <groupId>org.o7planning</groupId>
14
15
<artifactId>CommonsLoggingTutorial</artifactId>
16
17
18 <version>0.0.1-SNAPSHOT</version>
19
20
21
22
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
Trong bước này chúng ta sẽ làm một ví dụ đơn giản HelloWorld, nó sẽ ghi Log ra màn hình Console.
HelloWorld.java
?
1
2 package org.o7planning.tutorial.commonslogging;
3
4
5
6
7 import org.apache.commons.logging.Log;
8
9
import org.apache.commons.logging.LogFactory;
10
11
12
13
14
public class HelloWorld {
15
16
17
}
}
commons-logging.properties
1
2 org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
3
log4j.configuration=log4j.properties
log4j.properties
1
2 log4j.rootLogger=DEBUG, CA, NTEventLog
3
4
5
6
#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
commons-logging.properties
1
2 org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
3
log4j.configuration=log4j.xml
log4j.xml
1
2 <?xml version="1.0" encoding="UTF-8" ?>
3
4
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
5
6
7
8
9
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
10
11
12
13
14
<appender name="MyConsole" class="org.apache.log4j.ConsoleAppender">
15
16
17 <param name="Target" value="System.out" />
18
19
20 <layout class="org.apache.log4j.PatternLayout">
</layout>
</appender>
<root>
</root>
</log4j:configuration>
Chạy class HelloWorld và xem Log trên màn hình Console:
Tiếp theo chúng ta sẽ tiếp tục với một ví dụ phức tạp hơn, ghi Log ra file.
AdminApplication.java
?
1
2 package org.o7planning.tutorial.commonslogging.admin;
3
4
5
6
7 import org.apache.commons.logging.Log;
8
9
import org.apache.commons.logging.LogFactory;
10
11
12
13
14
public class AdminApplication {
15
16
17
18
19
20 private static final Log log = LogFactory.getLog(AdminApplication.class);
21
22
23
24
25 public static void main(String[] args) {
26
27 log.debug("Example debug message ..");
raiseException();
} catch (Exception e) {
FrontEndApplication.java
?
1
2 package org.o7planning.tutorial.commonslogging.frontend;
3
4
5
6
7 import org.apache.commons.logging.Log;
8
9
import org.apache.commons.logging.LogFactory;
10
11
12
13
14
public class FrontEndApplication {
15
16
17
18
}
}
Cấu hình thêm vào trong log4j.xml, thêm vào đoạn cấu hình:
1
2 <appender name="AdminFileAppender" class="org.apache.log4j.FileAppender">
3
4
<param name="File" value="logs/admin.log" />
5
6
7 <layout class="org.apache.log4j.PatternLayout">
8
9
<param name="ConversionPattern"
10
11
12 value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
13
14
</layout>
15
16
17 </appender>
18
19
20
21
22 <appender name="FrontEndFileAppender" class="org.apache.log4j.FileAppender">
23
24
25 <param name="File" value="logs/frontEnd.log" />
26
27 <layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
</appender>
<logger name="org.o7planning.tutorial.commonslogging.admin">
</logger>
<logger name="org.o7planning.tutorial.commonslogging.frontend">
</logger>
log4j.xml
?
1
2 <?xml version="1.0" encoding="UTF-8" ?>
3
4
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
5
6
7
8
9
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
10
11
12
13
14
<appender name="MyConsole" class="org.apache.log4j.ConsoleAppender">
15
16
17 <param name="Target" value="System.out" />
18
19
20 <layout class="org.apache.log4j.PatternLayout">
21
22 <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
23
24
25 </layout>
26
27 </appender>
28
29
30
31
32
33
34
35
36
37
38
39
40 <appender name="AdminFileAppender" class="org.apache.log4j.FileAppender">
41
42
43 <param name="File" value="logs/admin.log" />
44
45
<layout class="org.apache.log4j.PatternLayout">
46
47
48 <param name="ConversionPattern"
49
50
value="%d{dd MMM yyyy HH:mm:ss,SSS} {%t} %-5p %c %x - %m%n" />
</layout>
</appender>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
</layout>
</appender>
</logger>
<logger name="org.o7planning.tutorial.commonslogging.frontend">
</logger>
<root>
</root>
</log4j:configuration>
Có một chú ý về thứ tự các thẻ khi bạn cấu hình log4j.xml:
?
1
2 <?xml version="1.0" encoding="UTF-8" ?>
3
4
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
5
6
7
8
9
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
10
11
12
13
14
<!-- render -->
15
16
17 <renderer></renderer>
18
19
20 <renderer></renderer>
21
22 <renderer></renderer>
23
24
25
26
27 <!-- appender -->
28
29
30 <appender></appender>
31
32
<appender></appender>
33
34
35 <appender></appender>
36
37
38
39
40
41
42
43 <!-- plugin -->
44
45
<plugin></plugin>
46
47
<plugin></plugin>
<plugin></plugin>
<logger></logger>
<logger></logger>
<logger></logger>
<category></category>
<category></category>
<category></category>
<root></root>
<root></root>
<loggerfactory></loggerfactory>
<loggerfactory></loggerfactory>
<loggerfactory></loggerfactory>
<categoryfactory></categoryfactory>
<categoryfactory></categoryfactory>
<categoryfactory></categoryfactory>
</log4j:configuration>
Một thư mục logs đã được tạo ra và có 2 file log (admin.log & frontEnd.log)
Apache Org
Java cơ bản
Mục lục
Java cơ bản
Java cơ bản
Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học
tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:
langlearning.net
í dụ Encode và Decode
1- V
1- Ví dụ Encode và Decode
Một ví dụ sử dụng thư viện Apache Axis để mã hóa (encode) và giải mã (decode) một đoạn văn bản:
● http://mvnrepository.com/artifact/org.apache.axis/axis
* pom.xml *
1
2 <!-- http://mvnrepository.com/artifact/org.apache.axis/axis -->
3
4 <dependency>
5
6
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
EncodeDecodeExample.java
?
1
2 package org.o7planning.example.encode;
3
4
5
6
import java.io.UnsupportedEncodingException;
7
8
9
10
11 import org.apache.axis.encoding.Base64;
12
13
14
15
16 public class EncodeDecodeExample {
17
18
19
20
// Mã hóa một đoạn text
21
22
23 // Encode
24
25 public static String encodeString(String text)
26
27
throws UnsupportedEncodingException {
28
29
30 byte[] bytes = text.getBytes("UTF-8");
31
32 String encodeString = Base64.encode(bytes);
33
34
return encodeString;
35
36
37 }
38
39
40
// Giải mã hóa một đoạn text (Đã mã hóa trước đó).
// Decode
throws UnsupportedEncodingException {
return str;
Java cơ bản