Beruflich Dokumente
Kultur Dokumente
com/communityuni/
Năm 2016
Hướng dẫn:
Mỗi Module được thiết kế cho thời lượng là 6 tiết thực hành tại lớp với sự
hướng dẫn của giảng viên.
Tùy theo số tiết phân bổ, mỗi tuần học có thể thực hiện nhiều Module.
Sinh viên phải làm tất cả các bài tập trong các Module ở tuần tương ứng.
Những sinh viên chưa hòan tất phần bài tập tại lớp có trách nhiệm tự làm
tiếp tục ở nhà.
Các bài có dấu (*) là các bài tập nâng cao dành cho sinh viên khá giỏi.
Trang 1
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Mục lục
Module 1 : Ôn tập Graphic User Interface..................................................................... 3
Trang 2
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
MODULE 1
Mục đích:
Ôn tập Graphic User Interface, giúp các sinh viên hiểu được LayoutManager, Common Control,
Event, DialogBox, Advanced Control. Sinh viên phải thực hiện tốt Module 1 để ứng dụng cho
các Module tiếp theo, đặc biệt là phần kết nối cơ sở dữ liệu.
Bài tập 1: Thực hành cách hiển thị cửa sổ Windows trong Java
Hãy hiển thị cửa sổ trên, yêu cầu viết class kế thừa từ JFrame
Hướng dẫn:
Giải thích:
Trang 3
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
FlowLayout cho phép add các control trên cùng một dòng, khi nào hết chỗ chứa nó sẽ tự động
xuống dòng, ta cũng có thể điều chỉnh hướng xuất hiện của control. Mặc định khi một JPanel
được khởi tạo thì bản thân lớp chứa này sẽ có kiểu Layout là FlowLayout.
Hướng dẫn:
BoxLayout cho phép add các control theo dòng hoặc cột, tại mỗi vị trí add nó chỉ chấp nhận 1
control, do đó muốn xuất hiện nhiều control tại một vị trí thì bạn nên add vị trí đó là 1 JPanel rồi
sau đó add các control khác vào JPanel này.
Trang 4
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
BoxLayout.X_AXIS : Cho phép add các control theo hướng từ trái qua phải.
BoxLayout.Y_AXIS : Cho phép add các control theo hướng từ trên xuống dưới.
BoxLayout sẽ không tự động xuống dòng khi hết chỗ chứa, tức là các control sẽ bị che khuất
nếu như thiếu không gian chứa nó.
Hướng dẫn:
Trang 5
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Nếu như không có 4 vùng : North, West, South, East. Thì vùng Center sẽ tràn đầy cửa sổ, thông
thường khi đưa các control JTable, JTree, ListView, JScrollpane… ta thường đưa vào vùng
Center để nó có thể tự co giãn theo kích thước cửa sổ giúp giao diện đẹp hơn.
Trang 6
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Hướng dẫn: Sinh viên phải xác định Layout Manager trước, ta cũng có thể kế hợp các Layout để
thiết kế giao diện, đặt tên control theo yêu cầu bên dưới
Trang 7
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 6: thiết kế giao diện để thực hiện các phép toán : ‘+’ ‘-’ ‘*’ ‘:’
Thiết kế giao diện như hình bên dưới:
Khi bấm nút Giải thì tùy thuộc vào phép toán được chọn mà kết quả thực hiện khác nhau.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CongTruNhanChiaUI extends JFrame {
private static final long serialVersionUID = 1L;
public CongTruNhanChiaUI(String title)
{
setTitle(title);
}
public void doShow()
{
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addControl();
setResizable(false);
setVisible(true);
}
public void addControl()
{
JPanel pnBorder=new JPanel();
pnBorder.setLayout(new BorderLayout());
JPanel pnNorth=new JPanel();
JLabel lblTitle=new JLabel("Cộng Trừ Nhân Chia");
pnNorth.add(lblTitle);
pnBorder.add(pnNorth,BorderLayout.NORTH);
lblTitle.setForeground(Color.BLUE);
Font ft=new Font("arial", Font.BOLD, 25);
Trang 8
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
lblTitle.setFont(ft);
Border southborder
=BorderFactory.createLineBorder(Color.RED);
TitledBorder southTitleBorder=
new TitledBorder(southborder, "Chọn tác vụ");
pnWest.setBorder(southTitleBorder);
Border centerborder
=BorderFactory.createLineBorder(Color.RED);
TitledBorder centerTitleBorder=
new TitledBorder(centerborder, "nhập 2 số a và b:");
pnCenter.setBorder(centerTitleBorder);
pnCenter.add(pna);
pnc.add(pnpheptoan);
pnCenter.add(pnc);
lbla.setPreferredSize(lblkq.getPreferredSize());
lblb.setPreferredSize(lblkq.getPreferredSize());
btnThoat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int ret=JOptionPane.showConfirmDialog(null, "Muốn
thoát hả?", "Thoát", JOptionPane.YES_NO_OPTION);
if(ret==JOptionPane.YES_OPTION)
System.exit(0);
}
});
btnXoa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Trang 10
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
txta.setText("");
txtb.setText("");
txtkq.setText("");
txta.requestFocus();
}
});
btnGiai.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sa=txta.getText();
int a=0,b=0;
try
{
a=Integer.parseInt(sa);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Nhập sai
định dạng!");
txta.selectAll();
txta.requestFocus();
return;
}
String sb=txtb.getText();
try
{
b=Integer.parseInt(sb);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Nhập sai
định dạng!");
txtb.selectAll();
txtb.requestFocus();
return;
}
double kq=0;
if(radCong.isSelected())
{
kq=(a+b);
}
else if(radTru.isSelected())
{
kq=(a-b);
}
else if(radNhan.isSelected())
{
kq=(a*b);
}
else
Trang 11
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
{
kq=a*1.0/b*1.0;
}
txtkq.setText(kq+"");
}
});
Container con=getContentPane();
con.add(pnBorder);
}
public static void main(String[] args) {
CongTruNhanChiaUI ui=new CongTruNhanChiaUI("Cộng - Trừ - Nhân -
Chia");
ui.doShow();
}
}
- Chương trình cho phép nhập vào các số nguyên từ giao diện trong phần nhập thông tin,
Khi người sử nhập giá trị vào JTextField và click nút “Nhập” thì sẽ cập nhập dữ liệu
xuống JList, Nếu checked vào “Cho nhập số âm” thì các số âm mới được phép đưa vào
JList còn không thì thông báo lỗi.
- Ô Chọn tác vụ, sinh viên phải thực hiện toàn bộ các yêu cầu
- Nút Đóng chương trình: sẽ hiển thị thông báo hỏi người sử dụng có muốn đóng hay
không.
Trang 12
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Giao diện sẽ có 2 JButton: Start và Stop. Khi bấm Start chương trình sẽ hiển thị hình ảnh tuần tự
trong mảng 10 hình ảnh có sẵn. Bấm Stop để tạm dừng duyệt hình ảnh. Xem hình yêu cầu
Trang 14
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
pnCenter.setLayout(new CardLayout());
pnBorder.add(pnCenter,BorderLayout.CENTER);
pnCenter.setBackground(Color.RED);
JPanel []pnArr=new JPanel[10];
addImage(pnCenter,pnArr);
showImage(pnCenter,"card1");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.start();
timer.addActionListener(new TimerPanel(pnCenter));
}
});
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.stop();
}
});
Container con=getContentPane();
con.add(pnBorder);
}
private void addImage(JPanel pnCenter,JPanel []pnArr)
{
for(int i=0;i<pnArr.length;i++)
{
pnArr[i]=new JPanel();
JLabel lbl=new JLabel();
ImageIcon icon=new ImageIcon("E:\\hoa\\"+i+".jpg");
lbl.setIcon(icon);
pnArr[i].add(lbl);
pnCenter.add(pnArr[i],"card"+i);
}
}
public void showImage(JPanel pn,String cardName)
{
CardLayout cl=(CardLayout)pn.getLayout();
cl.show(pn, cardName);
}
private class TimerPanel implements ActionListener
{
JPanel pn=null;
public TimerPanel(JPanel pn) {
this.pn=pn;
}
public void actionPerformed(ActionEvent arg0) {
showImage(pn,"card"+pos);
pos++;
if(pos>=10)
pos=1;
}
}
public static void main(String[] args) {;
ImageAnimation imgUi=new ImageAnimation("Image Animation!");
imgUi.doShow();
}
Trang 16
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
}
Bài tập 10: Cải tiến bài tập 10. Chương trình sẽ cho phép đọc danh sách các hình ảnh bất kỳ
trong ổ đĩa. (*)
Hướng dẫn:
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
public class ImageAnimation2 extends JFrame{
private static final long serialVersionUID = 1L;
Timer timer;
private int pos=0;
public ImageAnimation2(String title)
{
super(title);
timer=new Timer(500, null);
}
public void doShow()
{
setSize(500,550);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addControl();
setVisible(true);
}
public void addControl()
{
JPanel pnBorder=new JPanel();
pnBorder.setLayout(new BorderLayout());
Trang 17
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.start();
timer.addActionListener(new TimerPanel(pnCenter));
}
});
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.stop();
}
});
btnBrowser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser jfc=new JFileChooser();
jfc.setMultiSelectionEnabled(true);
if(jfc.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
File []files=jfc.getSelectedFiles();
for(int i=0;i< files.length;i++)
{
File f=files[i];
ImageIcon icon=new ImageIcon(f.getPath());
JPanel pn=new JPanel();
Trang 18
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
}
private class TimerPanel implements ActionListener
{
JPanel pn=null;
public TimerPanel(JPanel pn) {
this.pn=pn;
}
public void actionPerformed(ActionEvent arg0) {
showImage(pn,"card"+pos);
pos++;
if(pos>=pn.getComponentCount())
pos=0;
}
}
public static void main(String[] args) {;
ImageAnimation2 imgUi=new ImageAnimation2("Image Animation!");
imgUi.doShow();
}
}
Bài tập 11: Thực hành về tạo Menu. Yêu cầu thiết kế Menu theo hình sau, ứng với mỗi menu
item sinh viên hãy cài đặt coding để hiển thị thông báo là đang chọn menu nào. (*)
Hướng dẫn: JMenuBarJMenuJMenuItem. Phải biết kết hợp các class này.
Yêu cầu giả lập Menu giống như chương trình Foxit Reader:
Trang 19
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 12: Thực hành về JToolBar, tương tự như câu 12, giả lập Toolbar của chương trình
Foxit Reader, ứng với mỗi lệnh trên JToolBar, sinh viên hãy xuấtt thông báo đang sử dụng chức
năng nào. (*)
Bài tập 13: Thiết kế giao diện như hình bên dưới - JTable: (*)
package baitap13;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Trang 20
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
tblModelAcc=new DefaultTableModel();
tblModelAcc.addColumn("Acc Number");
tblModelAcc.addColumn("Acc Name");
tblModelAcc.addColumn("Acc Money");
tblAcc=new JTable(tblModelAcc);
JScrollPane sc=new
JScrollPane(tblAcc,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCR
OLLBAR_AS_NEEDED);
con.add(sc,BorderLayout.CENTER);
Trang 21
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
lblAccName.setPreferredSize(lblAccNumber.getPreferredSize());
lblAccMoney.setPreferredSize(lblAccNumber.getPreferredSize());
addEvents();
}
public void addEvents()
{
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String
arr[]={txtAccNumber.getText(),txtAccName.getText(),txtAccMoney.getText()};
tblModelAcc.addRow(arr);
}
});
btnExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int ret=JOptionPane.showConfirmDialog(null, "Are you sure you
want to exit?", "Exit!", JOptionPane.YES_NO_OPTION);
if(ret==JOptionPane.YES_OPTION)
System.exit(0);
}
});
}
public void doShow()
{
myFrame.setSize(400, 300);
myFrame.setLocationRelativeTo(null);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
package baitap13;
/**
* @param args
*/
public static void main(String[] args) {
AccUI ui=new AccUI();
ui.doShow();
}
Trang 22
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
MODULE 2
Mục đích:
Thực hành MultiThreading, hiểu được Thread, Runnable, Swings với Threading
Trang 23
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 5: Thiết lập độ ưu tiên cho Thread (dùng phương thức setPriority), có 3 độ ưu tiên căn
bản : MAX_PRIORITY (10), NORM_PRIORITY(5), MIN_PRIORITY(1). Chúng ta có thể
thiết lập độ ưu tiên tùy ý từ 1 tới 10.
Trang 24
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang 25
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 7: Hãy viết chương trình Demo chuyển khoản ngân hàng
Yêu cầu : Phải đồng bộ dữ liệu giữa các lần gửi tiền / Rút tiền
Mục đích : Hiểu được Race Condition, ReentrantLock , synchronized…
Ví dụ về Race Condition.
Class Bank
/**
A bank with a number of bank accounts.
*/
public class Bank {
/**
Constructs the bank.
@param n the number of accounts
@param initialBalance the initial balance
for each account
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
for (int i = 0; i < accounts.length; i++)
accounts[i] = initialBalance;
}
/**
Transfers money from one account to another.
@param from the account to transfer from
@param to the account to transfer to
Trang 26
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
/**
Gets the sum of all account balances.
@return the total balance
*/
public double getTotalBalance()
{
double sum = 0;
return sum;
}
/**
Gets the number of accounts in the bank.
@return the number of accounts
*/
public int size()
{
return accounts.length;
}
Class TransferRunnable
/**
A runnable that transfers money from an account to other
accounts in a bank.
*/
public class TransferRunnable implements Runnable {
/**
Constructs a transfer runnable.
@param b the bank between whose account money is transferred
@param from the account to transfer money from
Trang 27
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Class UnsynchBankTest
public class UnsynchBankTest
{
public static void main(String[] args)
{
Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE);
int i;
for (i = 0; i < NACCOUNTS; i++)
{
TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE);
Thread t = new Thread(r);
t.start();
}
}
public static final int NACCOUNTS = 100;
public static final double INITIAL_BALANCE = 1000;
}
Trang 28
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Kết quả ta thấy dữ liệu không được đồng bộ, cho du chuyển / nhận sảy ra thì tổng tiền cũng
phải giữ nguyên, ở đây nó bị thay đổi, nguyên nhân gây ra là do Race Condition
Trang 29
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Chúng ta có thể đồng bộ bằng cách tiếp cận ReentrantLock. Dưới đây là code minh họa:
Class Bank
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
A bank with a number of bank accounts.
*/
public class Bank {
/**
Constructs the bank.
@param n the number of accounts
@param initialBalance the initial balance
for each account
*/
public Bank(int n, double initialBalance)
{
accounts = new double[n];
for (int i = 0; i < accounts.length; i++)
accounts[i] = initialBalance;
bankLock = new ReentrantLock();
sufficientFunds = bankLock.newCondition();
}
/**
Transfers money from one account to another.
@param from the account to transfer from
@param to the account to transfer to
@param amount the amount to transfer
*/
public void transfer(int from, int to, double amount)
throws InterruptedException
{
bankLock.lock();
try
{
while (accounts[from] < amount)
sufficientFunds.await();
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
sufficientFunds.signalAll();
}
finally
{
bankLock.unlock();
}
}
/**
Gets the sum of all account balances.
@return the total balance
*/
public double getTotalBalance()
{
Trang 30
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
bankLock.lock();
try
{
double sum = 0;
return sum;
}
finally
{
bankLock.unlock();
}
}
/**
Gets the number of accounts in the bank.
@return the number of accounts
*/
public int size()
{
return accounts.length;
}
Class TransferRunnable
/**
A runnable that transfers money from an account to other
accounts in a bank.
*/
public class TransferRunnable implements Runnable {
/**
Constructs a transfer runnable.
@param b the bank between whose account money is transferred
@param from the account to transfer money from
@param max the maximum amount of money in each transfer
*/
public TransferRunnable(Bank b, int from, double max)
{
bank = b;
fromAccount = from;
maxAmount = max;
}
Trang 31
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Class SynchBankTest
/**
This program shows how multiple threads can safely access a data structure.
*/
public class SynchBankTest
{
public static void main(String[] args)
{
Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE);
int i;
for (i = 0; i < NACCOUNTS; i++)
{
TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE);
Thread t = new Thread(r);
t.start();
}
}
Bài tập 8 : Tiếp tục với bài chuyển khoản ở câu 7, yêu cầu thiết kế giao diện như hình dưới đây
để thực hiện chức năng chuyển khoản. Bấm vào Start chương trình sẽ tiến hành chuyển khoản
trên giao diện, khi bấm Stop chương trình sẽ dừng chuyển khoản.
Trang 32
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 9: Dùng đa tiến trình để cập nhập dữ liệu cho JProgressBar. Giao diện chương trình như
bên dưới.
Coding mẫu :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
class myRun implements Runnable
{
JProgressBar proBar=null;
public myRun(JProgressBar bar)
{
proBar=bar;
}
public void run() {
int x=0;
while(x<=100) {
proBar.setValue(x);
x++;
try {Thread.sleep(1000);}
catch (InterruptedException e) {}
}
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Done");
}
}
public class ProgressSample {
public static void main(String args[]) {
JFrame f = new JFrame("JProgressBar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
JButton btn=new JButton("Start");
JPanel pn=new JPanel();
content.add(pn, BorderLayout.SOUTH);
pn.add(btn);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Thread t1=new Thread(new myRun(progressBar));
t1.start(); }
});
f.setSize(300, 120);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Trang 33
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 10: Dùng đa tiến trình để minh họa các thuật toán sắp xếp như giao diện bên dưới: (*)
MODULE 3
Mục đích:
Thực hành về Collections, giúp sinh viên hiểu được : ArrayList, LinkedList, Vector, Hash table,
HashSet, LinkedHashSet, TreeSet, HashMap, TreeMap, PriorityQueue, Properties.
Bài tập 1 : Viết chương trình quản lý sinh viên dưới dạng console, yêu cầu sử dụng ArrayList
hoặc LinkedList hoặc Vector và thực hiện các chức năng sau (thông tin sinh viên bao gồm : mã
số sinh viên, họ tên, năm sinh, địa chỉ, lớp học):
a) Cho phép thêm, sửa, xóa danh sách sinh viên
b) Xuất ra số lượng sinh viên
c) Xuất ra danh sách các sinh viên thuộc một lớp học bất kỳ nhập vào từ bàn phím
d) Cho phép lưu/mở danh sách sinh viên trên ổ cứng
package chap2.quanlysinhvien;
import java.util.Date;
public class Sinhvien {
private String Masv;
private String Tensv;
private Date Namsinh;
private String Diachi;
private String Lop;
public String getMasv() {
return Masv;
}
public void setMasv(String masv) {
Masv = masv;
}
public String getTensv() {
return Tensv;
}
public void setTensv(String tensv) {
Tensv = tensv;
}
public Date getNamsinh() {
return Namsinh;
}
public void setNamsinh(Date namsinh) {
Namsinh = namsinh;
}
public String getDiachi() {
return Diachi;
}
public void setDiachi(String diachi) {
Diachi = diachi;
}
public String getLop() {
return Lop;
}
public void setLop(String lop) {
Lop = lop;
}
public String toString() {
return "Sinhvien [Masv=" + Masv + ", Tensv=" + Tensv + ", Namsinh="
+ Namsinh + ", Diachi=" + Diachi + ", Lop=" + Lop + "]";
}
Class DanhSachSinhvien
package chap2.quanlysinhvien;
import java.util.ArrayList;
public class DanhSachSinhvien {
private ArrayList<Sinhvien> dsSv=new ArrayList<Sinhvien>();
public boolean ktTrungma(String masv)
{
for(Sinhvien sv : dsSv)
{
if(sv.getMasv().equalsIgnoreCase(masv))
return true;
}
return false;
}
Trang 35
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Class TestSinhvien
package chap2.quanlysinhvien;
public class TestSinhvien {
public static void main(String[] args) {
DanhSachSinhvien qlsv=new DanhSachSinhvien();
Sinhvien teo=new Sinhvien();
teo.setMasv("113");
teo.setTensv("Nguyễn Văn Tèo");
qlsv.addSinhvien(teo);
Sinhvien ty=new Sinhvien();
ty.setMasv("114");
ty.setTensv("Nguyễn Thị tý");
qlsv.addSinhvien(ty);
System.out.println(qlsv);
}
Trang 36
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 2: Thêm chức năng sắp xếp danh sách sinh viên theo mã số ở bài tập 1.
Bài tập này giúp sinh viên hiểu được chức năng sort của Collections và interface Comparable
Để sắp xếp được các sinh viên theo mã số thì class Sinh viên phải implements interface
Comparable đồng thời chúng ta phải override phương thức compareTo.
Coding mẫu cho bài này như sau:
package chap2.quanlysinhvien;
import java.util.Date;
public class Sinhvien implements Comparable<Sinhvien>{
private String Masv;
…//code here…
public String getMasv() {
return Masv;
}
public int compareTo(Sinhvien o) {
if(Masv.equalsIgnoreCase(o.getMasv()))
return 0;
return 1;
}
package chap2.quanlysinhvien;
import java.util.ArrayList;
import java.util.Collections;
}
Khi nào muốn sắp xếp danh sách chúng ta chỉ cần gọi hàm sort trong class trên.
public class TestSinhvien {
public static void main(String[] args) {
DanhSachSinhvien qlsv=new DanhSachSinhvien();
Sinhvien teo=new Sinhvien();
teo.setMasv("113");
teo.setTensv("Nguyễn Văn Tèo");
qlsv.addSinhvien(teo);
Sinhvien ty=new Sinhvien();
ty.setMasv("114");
ty.setTensv("Nguyễn Thị tý");
qlsv.addSinhvien(ty);
qlsv.sort();
System.out.println(qlsv);
Trang 37
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 3: Hiệu chỉnh bài tập 1 về dạng Graphic User Interface, giao diện như bên dưới:
Yêu cầu:
- Sử dụng SimpleDateFormat để định dạng nhập năm sinh.
- Nút Thêm cho phép xóa trắng dữ liệu ở mục thông tin chi tiết và cho phép nhập dữ liệu
mới vào, khi nhấp nút Lưu sẽ lưu thông tin xuống ArrayList đồng thời cập nhập JTable.
- Nút Lưu dùng để lưu sinh viên vào danh sách ArrayList, nếu mã tồn tại thì tự động gọi
hàm cập nhập thông tin.
- Nút xóa cho phép xóa sinh viên đang chọn trong JTable.
- Mỗi lần click vào từng dòng trong JTable thì sẽ hiển thị thông tin chi tiết của sinh viên
vào phần thông tin chi tiết.
- Nút Lưu tập tin cho phép lưu danh sách sinh viên xuống ổ cứng (map đối tượng)
- Nút Mở tập tin cho phép load danh sách sinh viên trong tập tin lên JTable
- Nút thoát : khi nào người sử dụng chọn nút này thì sẽ hiển thị thông báo hỏi người sử
dụng có chắc chắn muốn thoát hay không? Nếu muốn thoát thì sẽ đóng chương trình, nếu
không thì giữ nguyên màn hình.
*** Chú ý, những bài này là tiền đề để vào chương JDBC chúng ta sẽ tiếp tục sử dụng
lại, do đó sinh viên phải hiểu cách tạo giao diện, gán sự kiện cũng như cách sử dụng các
collections.
Trang 38
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Coding mẫu cho phần giao diện (phần xử lý thông tin sinh viên tự thực hiện):
package chap2.quanlysinhvien;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class QlsvUI extends JFrame{
private static final long serialVersionUID = 1L;
JTextField txtMa,txtTen,txtNamsinh,txtDiachi,txtLop;
JButton btnThemmoi,btnLuu,btnXoa,btnMotaptin,btnLuutaptin,btnThoat;
JTable tblSinhvien;
DefaultTableModel model;
public QlsvUI(String title)
{
super(title);
addControl();
}
public void addControl()
{
Container con=getContentPane();
con.setLayout(new BorderLayout());
JPanel pnGeneral=new JPanel();
pnGeneral.setLayout(new BorderLayout());
con.add(pnGeneral,BorderLayout.CENTER);
pnDetail.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(C
olor.BLUE), "Thông tin chi tiết"));
pnNorth.add(pnDetail);
pnDetail.add(pnMa);
pnTable.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Co
lor.BLUE), "Danh sách sinh viên"));
model=new DefaultTableModel();
model.addColumn("Mã");
model.addColumn("Tên");
model.addColumn("Năm sinh");
model.addColumn("Địa chỉ");
model.addColumn("Lớp");
tblSinhvien=new JTable(model);
JScrollPane sc=new JScrollPane(tblSinhvien,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pnTable.add(sc,BorderLayout.CENTER);
pnGeneral.add(pnTable,BorderLayout.CENTER);
pnButton2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(
Color.RED), "Nhập xuất"));
btnMotaptin =new JButton("Mở tập tin");
pnIo.add(btnMotaptin);
btnLuutaptin=new JButton("Lưu tập tin");
pnIo.add(btnLuutaptin);
pnButton2.add(pnIo,BorderLayout.WEST);
lblMa.setPreferredSize(lblDiachi.getPreferredSize());
lblLop.setPreferredSize(lblDiachi.getPreferredSize());
lblTen.setPreferredSize(lblDiachi.getPreferredSize());
}
public void doShow()
{
setSize(600, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
QlsvUI ui=new QlsvUI("Quản lý sinh viên");
ui.doShow();
}
}
Hashtable đi theo Key và Value. Nếu Key trùng nhau thì nó sẽ lấy theo Key thứ 2.
Hashtable cung cấp nhiều hàm hữu ích : put, get, remove, elements… tùy vào từng trường hợp
mà chúng ta ứng dụng cho phù hợp, dưới đây cung cấp một số ví dụ về Hashtable, yêu cầu sinh
viên thực hiện và cho nhận xét.
package chap1.myHashTable;
public class Person {
private String Id;
private String Name;
public String getId() {
return Id;
}
Trang 41
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
package chap1.myHashTable;
import java.util.Enumeration;
import java.util.Hashtable;
public class TestHashTable {
public static void main(String[] args) {
Hashtable<String, Person> hashTbl=new Hashtable<String, Person>();
hashTbl.put("1", new Person("1", "teo"));
Person p=new Person("2", "ty");
if(hashTbl.containsKey(p.getId()))
{
System.out.println("Trung");
}
else
hashTbl.put(p.getId(), p);
hashTbl.put(p2.getId(), p2);
hashTbl.remove("1");
System.out.println(hashTbl);
Person px= hashTbl.get("3");
Enumeration<Person> list=hashTbl.elements();
while(list.hasMoreElements())
{
Person x=list.nextElement();
System.out.println(x);
}
}
}
Sinh viên có thể dựa vào ví dụ này để đọc cơ sở dữ liệu và đổ vào Hashtable, với Key chính là
khóa chính, còn Value chính là đối tượng trong từng dòng dữ liệu.
Bài tập 5: Sinh viên hiệu chỉnh bài tập 3, thay vì sử dụng ArrayList để quản lý danh sách sinh
viên, bây giờ chúng ta phải sử dụng Hashtable để quản lý nhân sự (dùng class Person ở bài 4).
Trang 42
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 6: Thực hành với HashSet , hãy so sánh sự khác biệt giữa HashSet , Hashtable và
ArrayList.
Sinh viên thực hiện ví dụ mẫu bên dưới, từ đó ứng dụng để viết chương trình quản lý sản phẩm.
package chap2.myHashSet;
package chap2.myHashSet;
import java.util.HashSet;
import java.util.Iterator;
}
}
Bài tập 7: Hiệu chỉnh bài tập 6, yêu cầu sử dụng LinkedHashSet để quản lý sản phẩm. Sinh
viên hãy cho biết sự khác biệt giữa HashSet và LinkedHashSet.
Bài tập 8 : Viết chương trình biểu diễn 1 từ điển trong máy tính. Gợi ý: Sử dụng
TreeMap<String,WordObject> để lưu trữ tập các từ. Mỗi từ ở đây là 1 đối tượng gồm các thuộc
tính: từ (khóa của đối tượng), phát âm, loại từ, ghi chú.
Kết quả như hình sau:
Bài tập 9: Viết chương trình quản lý bài hát, yêu cầu sử dụng HashMap.
Trang 44
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
MODULE 4
Mục đích:
Thực hành về Networking. Module này giúp sinh viên hiểu được về InetAddress, Socket, RMI
SOCKET PROGRAMMING
Bài tập 1:
Viết 1 chương trình có tên Calculator_server nhận 1 biểu thức gồm 2 chữ số và 1 phép toán sau
đó thực thi biểu thức này và gửi kết quả lại cho client.
Sữa chữa chương trình cho phép nhiều client kết nối cùng lúc.
Phía client, viết giao diện gồm 2 JtextField cho việc nhập số, 1 JLabel cho việc xuất kết quả.
Các nút Cộng, trừ, nhân,chia, clear và thoát.
Giao diện cho client như sau:
Bài tập 2:
Viết chương trình giải phương trình bậc 2, server lắng nghe tại port 8189, cho phép chạy nhiều
client. Yêu cầu viết theo 3 trường hợp (dùng Text Stream, Data Stream, Object Stream) Giao
diện được cho như bên dưới:
try
{
InputStream in=m_soc.getInputStream();
Scanner sc=new Scanner(in);
double a=sc.nextDouble();
double b=sc.nextDouble();
double c=sc.nextDouble();
String sKq=processInfomation(a,b,c);
OutputStream out=m_soc.getOutputStream();
PrintWriter printOut=new PrintWriter(out,true);
printOut.println(sKq);
m_soc.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public CClientPtb2TextStream()
{
createUI();
}
private void createUI()
Trang 48
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
{
setLayout(new BorderLayout());
JPanel pnNorth=new JPanel();
pnNorth.setBackground(Color.CYAN);
JLabel lblNorth=new JLabel("Giải Phương Trình Bậc 2");
pnNorth.add(lblNorth);
Container con=getContentPane();
con.add(pnNorth,BorderLayout.NORTH);
soc.close();
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
private class CMyEvent implements ActionListener
{
@Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
Object o=arg0.getSource();
if(o.equals(btnSend))
{
proccessInformation();
}
else if(o.equals(btnClear))
{
clearText();
}
else if(o.equals(btnExit))
{
System.exit(0);
}
}
}
/**w
* @param args
*/
Trang 50
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
package duythanhwordpress.com.chapter3.ptb2textstream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Tới đây Sinh viên chạy class Test Server (CServerPtb2TextStream) trước, sau đó chạy class
Test Client (CClientPtb2TextStream)
Trang 51
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
- Trường hợp sử dụng Data Stream, sửa lại 2 chỗ gửi/ nhận bên Client và Server như sau:
Bên client :
private void doSend()
{
try
{
Socket soc=new Socket("localhost",8189);
OutputStream out=soc.getOutputStream();
DataOutputStream dataout=new DataOutputStream(out);
dataout.writeDouble(Double.parseDouble(txta.getText()));
dataout.writeDouble(Double.parseDouble(txtb.getText()));
dataout.writeDouble(Double.parseDouble(txtc.getText()));
InputStream in=soc.getInputStream();
DataInputStream datain=new DataInputStream(in);
txtkq.setText(datain.readUTF());
soc.close();
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
Bên Server:
public void run()
{
try
{
InputStream in=m_soc.getInputStream();
DataInputStream datain=new DataInputStream(in);
String strKq=processInformation
(datain.readDouble(),
datain.readDouble(),
datain.readDouble());
OutputStream out=m_soc.getOutputStream();
DataOutputStream dataout=new DataOutputStream(out);
dataout.writeUTF(strKq);
m_soc.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Với processInformation là hàm xử lý giải phương trình bậc 2, trả về kết quả sau khi nhận thông
số từ client gửi lên (Sinh viên tự viết thuật toán giải pt bậc 2 trong hàm này).
Trang 52
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
- Trường hợp sử dụng Object Stream, Ta nên viết 1 class tên là CPTB2, class này
implements Serializable. Sau đó sửa lại 2 chỗ gửi/ nhận bên Client và Server như sau:
Bên client :
private void doSend()
{
try
{
Socket soc=new Socket("localhost",8189);
OutputStream out=soc.getOutputStream();
ObjectOutputStream objout=new ObjectOutputStream(out);
CPTB2 pt2=new CPTB2(
Double.parseDouble(txta.getText()),
Double.parseDouble(txtb.getText()),
Double.parseDouble(txtc.getText()));
objout.writeObject(pt2);
InputStream in=soc.getInputStream();
ObjectInputStream objin=new ObjectInputStream(in);
CPTB2 pt2FromServer=(CPTB2) objin.readObject();
txtkq.setText(pt2FromServer.getKetQua());
soc.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Bên Server:
public void run()
{
try
{
InputStream in=m_soc.getInputStream();
ObjectInputStream objin=new ObjectInputStream(in);
CPTB2 pt2=(CPTB2) objin.readObject();
pt2.comPute();
OutputStream out=m_soc.getOutputStream();
ObjectOutputStream objout=new ObjectOutputStream(out);
objout.writeObject(pt2);
m_soc.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Trang 53
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Class CPTB2
package duythanhwordpress.com.chapter3.ptb2objectstream;
import java.io.Serializable;
}
Bài tập 3:
Viết 1 server cho phép nhiều client kết nối cùng lúc với các yêu cầu sau:
Client có thể gửi yêu cầu là đường dẫn đến 1 ổ điã hoặc 1 thư mục nào đó bất kỳ trên server.
Nếu đường dẫn đó tồn tại thị sẽ gửi về danh sách các thư mục con và các tập tin trong ổ đĩa /
đường dẫn đó.
Thiết kế client với cơ chế GUI nhận kết quả từ server và biểu diễn kết quả nhận được lên 1
JTree.
Hướng dẫn:
Đoạn code sau liệt kê tất cả thư mục, tập tin trong 1 đường dẫn path cho trước rồi đưa vào 1 đối
tượng ArrayList
OutputStream os = income.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(lstFiles);
oos.flush();
ObjectInputStream ois=new
ObjectInputStream(soc.getInputStream());
ArrayList<File>list=(ArrayList<File>)ois.readObject();
Trang 55
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 4:
Cải tiến bài tập 3 thành 1 chương trình quản lý thư mục từ xa và cho phép các thao tác cơ bản
như download, delete files / folders.
Bài tập 5:
Viết 1 chương trình từ điển cho phép tra từ qua mạng. VIệc tra từ này phải đảm bảo nhiều người
có thể tra cùng lúc. Việc thiết kế chương trình gồm 2 phần: Phần server và phần client.
Phần server: chỉ sẽ được chạy trên server có giao diện như sau:
Khi người dùng start server từ điển, server này sẽ lắng nghe trên cổng 2520 và sẽ nhận đầu vào
là từ cần tra sau đó thực hiện việc tra từ và trả kết quả về cho client hoặc là 1 đối tượng từ đã tra
trong trường hợp tra thành công, hoặc là null nếu từ không tồn tại.
Phần Client: sẽ được triển khai ở phía client, có giao diện như sau
Trang 56
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 6:
Viết chương trình tạo ra một bàn phím trên 2 máy tính A và B. viết chương trình điều khiển các
sự kiện nhấn phím trên máy tính B thông qua máy tính A và hiện kết quả lân màn hình của máy
B( thí dụ: khi nhấn một phím trên máy A cũng tương ứng với việc nhấn phím đó trên máy tính
B)
Bài tập 7:
Viết chương trình giả lập 1 chat room. Người dùng nhập địa chỉ server, tên nick chat vào và có
thể chat cùng nhau trên chat room này.
Trang 57
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang 58
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
UDP PROGRAMMING
Bài tập 1:
Viết 1 chương trình làm server sử dụng UDP cho phép lắng nghe trên cổng 2520. Khi client gửi
yêu cầu đến thì server này sẽ gửi 1 file hình ảnh về client. Ở phía client, sau khi nhận được
image từ server thì lưu image này xuống file đồng thời hiển thị lên 1 JFrame.
Bài tập 2:
Viết chương trình làm server sử dụng UDP cho phép lắng nghe trên cổng 7777. Khi client gửi
yêu cầu đến thì server này sẽ gửi 1 file audio/video về client. Ở phía client, sau khi nhận được
file audio/video từ server sẽ lưu file này xuống đĩa và cho thực thi file vừa nhận được.
Coding mẫu:
Server:
Trang 59
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Client:
Bài tập 3: Cải tiến bài tập 2, chương trình cho phép kết nối cùng lúc nhiều client tới server để
lấy tập tin về. Giao diện server như sau:
- Khi bấm vào Start, chương trình sẽ khởi động server tại port được nhập trên giao diện.
- Khi bấm Stop, sẽ thoát chương trình
Thiết kế giao diện client như bên dưới, cho phép người sử dụng chọn tập tin trên server để
download (hình ảnh), sau đó hiển thị lên giao diện:
Trang 60
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
- Chú ý là chương trình cho phép chạy đồng thời nhiều client truy suất lên server (kết hợp
Multithreading + Networking).
- Bên phải màn hình có JList, khi người sử dụng bấm vào nút Get Files thì chương trình có
nhiệm vụ lên server lấy toàn đường dẫn các tập tin nằm trong Server Path.
- Khi bấm vào nút Download, chương trình sẽ dùng UDP tải tập tin đang chọn trong JList,
lưu về máy client với tên mới được nhập trong ô New File Name. Sau khi tải xong tập tin
thì tự động mở tập tin này lên giao diện (nhìn bên trái màn hình).
- Khi có lỗi sảy ra thì chương trình phải hiển thị thông báo lỗi, tương tự như thông báo lỗi
dưới đây :
Trang 61
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
RMI PROGRAMMING
Các bước tạo ứng dụng RMI (4 bước):
Bước 1: Tạo một interface kế thừa từ class Remote
Bước 2: Tạo một class thực thi interface ở bước 1 đồng thời kế thừa UnicastRemoteObject
Trang 62
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 1:
Viết chương trình dùng kỹ thuật RMI cho việc chuyển đổi tiền tệ. Chương trình cho phép nhập
vào số tiền, chọn loại tiền (USD/VND) rồi tính toán. Giao diện client như sau:
Bài tập 2:
Viết chương trình dùng kỹ thuật RMI cho việc tính toán các số với các phép tính cơ bản. Client
sử dụng cơ chế đồ họa như sau:
Bài tập 3:
Viết chương trình bói online, kết hợp chuyển lịch âm thành lịch dương. Giao diện Server như
sau:
- Nhiệm vụ của Server là nhận 3 thông số: ngày, tháng, năm từ client và tiến hành giải mã
- Khi bấm Start Server, chương trình sẽ đăng ký RMI object đúng như thông số trên giao
diện mà người sử dụng nhập, chuỗi URL tự động được nối khi bấm Start thành công.
- Khi bấm Shutdown, chương trình sẽ tắt.
Trang 63
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
- Khi bấm vào Connect, chương trình sẽ kết nối để truy suất tới RMI object
- Khi bấm vào nút Bắt đầu bói, chương trình sẽ gửi thông số ngày âm lên server và nhận
kết quả trả về là ngày dương và thông tin bói chi tiết cho ngày tháng năm âm này.
- Bấm vào nút thoát để thoát khỏi chương trình.
Bài tập 4: Dùng kỹ thuật RMI để viết chương trình giải phương trình bậc 2, giao diện như sau:
Trang 64
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
MODULE 5
Mục đích:
Thực hành về JDBC, Module này giúp sinh viên kết nối tới Ms Access, SQL Server, MySQL.
Thực hiện được các chức năng : lấy dữ liệu, thêm, sửa , xóa... Có thể ứng dụng để viết các
chương trình quản lý.
Ví dụ về kết nối với nhiều hệ cơ sở dữ liệu, sinh viên xem trên blog này :
http://tranduythanh.blog.com/2012/03/28/k%E1%BA%BFt-n%E1%BB%91i-cac-h%E1%BB%87-
c%C6%A1-s%E1%BB%9F-d%E1%BB%AF-li%E1%BB%87u-b%E1%BA%B1ng-java-2/
Trang 65
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 1:
Làm các demontraction về kết nối CSDL và thực thi các phưong thức của đối tựong
Statement,PrepareStatement:
-executeQuery
- executeUpdate
- executeBatch
Bài tập 2: Thao tác trên ResultSet
Cho cơ sở dữ liệu tên là QLSV với cuấ trúc bảng đựoc cho như sau:
Trang 66
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Nhấn Hủy hoặc lưu, sau khi thực hiện xong tácc vụ sẽ khôi phục giao diện trở lại như ban đầu.
Khi nhấn nút Sửa
Khi nhấn nút “Xem danh sách sinh viên lớp hiện tại, 1 cửa sổ như sau xuất hiện hiển thị các sinh
viên thuộc lớp hiện tại đang được chọn
Trang 67
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang 68
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Tạo cơ sở dữ liệu theo mô hình trên trên hệ quản trị CSDL Access hoặc SQL server 2008.
Tạo form logon như hình sau:
Khi user nhấn nút logon, chương trình sẽ kiểm tra user và password rồi hiển thị thông báo chính
xác cần thiết nếu user không đăng nhập được.
Nếu user đăng nhập thành công, chương trình sẽ lưu trữ 1 mẫu tin xuống bảng tblSession đồng
thời lấy về tất cả các quyền mà user đang có trên bảng tblPrivileges.
Khi hiển thị chương trình chính. Tùy theo quyền mà user đang có, các menu của chương trình
chính sẽ được enable hoặc disable.
Hãy tạo các form để quản lý users. Các chức năng thêm,xóa, sửa, cập nhật, tìm kiếm,…chức
năng cấp quyền cho users.
Trang 69
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Tạo form để theo dõi các lần đăng nhập của các user (tracking).
Bài tập 5: CallableStatement
Viết chương trình demo cho phép thực thi các loại stored Procedure có tính chất sau:
a. Không có tham số
b. Có tham số IN
c. Có tham số OUT
d. Có tham số INOUT
e. Trả về 1 giá trị
Bài tập 6: Metadata
Viết chương trình cho phép kết nối vào 1 database của MS SQL server sau đó lấy danh sách các
bảng hiển thị lên 1 JTree. Khi người dùng chọn 1 phần tử trên Jtree: nếu là Table thì hiển thị cấu
trúc của nó đồng thời hiển thị dữ liệu. Nếu người dụng chọn 1 StoredProcedure thì hiển thị nội
dung của câu sql tạo storedproc này.
Viết 1 Form cho phép người dùng gõ vào 1 câu SQL và cho thực thi câu SQL này.
Trang 70
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 7: Viết chương trình quản lý sản phẩm, giao diện như bên dưới:
- Sinh viên tự thiết kế cơ sở dữ liệu hợp lý để thực hiện các yêu cầu sau:
o CSDL gồm có 2 bảng: Bảng Danh mục và bảng Sản phẩm
o Khi chương trình bắt đầu khởi động thì load toàn bộ danh mục sản phẩm vào JList
bên trái màn hình và load vào JCombobox bên phải màn hình.
o Khi bấm vào từng danh mục sản phẩm thì hiển thị danh sách các sản phẩm của
danh mục đó vào JTable bên phải màn hình.
o Khi chọn từng Sản phẩm trong JTable, chương trình sẽ hiển thị thông tin chi tiết
của sản phầm đó vào mục chi tiết ở góc phải bên dưới màn hình
o Khi bấm vào nút New bên Danh mục sản phẩm, chương trình sẽ hiển thị cửa sổ
cho phép nhập mới một danh mục sản phẩm vào cơ sở dữ liệu khi người sử dụng
click nút OK:
Trang 71
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
o Khi bấm vào nút Update bên Danh mục sản phẩm, chương trình sẽ hiển thị thông
tin chi tiết của danh mục đang chọn để cho phép người sử dụng sửa lại tên danh
mục:
o
o Khi bấm nút Remove bên Danh mục sản phẩm, chương trình sẽ xóa danh mục sản
phẩm đang chọn. Chú ý rằng nếu Danh mục này đã có sản phẩm bên trong thì phải
thông báo cho người sử dụng biết và hỏi xem có muốn xóa tất cả luôn hay không.
o Khi bấm nút New bên phần sản phẩm: xóa trắng các JTextField, cho phép người
sử dụng nhập mới 1 sản phẩm theo từng danh mục
o Khi bấm nút Save: chương trình sẽ lưu thông tin của sản phẩm, Nếu như mã tồn
tại thì tự động update, còn mã chưa tồn tại thì thực hiện lưu mới sản phẩm.
o Khi bấm nút Remove bên phần sản phẩm: chương trình sẽ xóa sản phẩm đang
chọn trong JTable.
o Menu File: Sẽ có 2 mục menu con; Menu 1 tên là Print cho phép in ấn toàn bộ
danh mục sản phẩm và các sản phẩm bên trong danh mục. Menu 2 tên là Exit, cho
phép thoát khỏi chương trình.
- Để in ấn chúng ta implements Printable, sinh viên có nhiệm vụ tìm hiểu chức năng in ấn
trên internet.
- Để hiển thị thông báo hỏi người sử dụng có chắc chắn muốn thoát hay không, ta dùng
đoạn code dưới đây:
if(JOptionPane.showConfirmDialog
(this, "Bạn có chắc chắn muốn thoát không?","Thôngbáo",
JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
System.exit(0);
Trang 72
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Cho Cơ Sở Dữ Liệu tên dbLibraries với cấu trúc bảng được mô tả dưới đây:
Bảng tblPublisher Dùng để lưu danh sách các nhà xuất bản, khóa chính là PublisherCode, Một nhà
xuất bản sẽ có một hoặc nhiều đầu sách
tblPublisher
Columns Name Data Type Data Size Description
PublisherCode VARCHAR 100 Mã nhà xuất bản ( khóa chính)
PublisherName NVARCHAR Tên nhà xuất bản
Address NVARCHAR Địa chỉ
Phone NVARCHAR Điện thọai
Bảng tblBook dùng để lưu danh sách các đầu sách, khóa chính là BookCode, khóa ngoại là
PublisherCode, Khóa ngoại này sẽ tham chiếu tới cột PublisherCode ở trong bảng tblPublisher
tblBook
Columns Name Data Type Data Size Description
BookCode VARCHAR 100 Mã sách ( khóa chính)
BookName NVARCHAR Tên sách
PublisherCode VARCHAR 100 Mã nhà xuất bản(khóa ngọai)
Dữ liệu mẫu:
Dữ liệu mẫu của bảng tblPublisher( bảng nhà xuất bản)
tblPublisher
PublisherCode PublisherName Address Phone
P020202021 Addison Wesley 75 Arlington St., Suite 300, Boston, 113-114-
MA 0115
P020202022 John Wiley and 605 Third Ave., New York, NY 113-112-
Sons 0117
P020202023 McGraw Hill 121 Ave. of The Americas, New York, 113-110-
NY 0118
P020202024 Wrox 10475 Crosspoint Blvd., Indianapolis, 114-114-
IN 0119
P020202025 Prentice Hall PTR 49 Sandiego, USA 110-115-
0113
Dữ liệu mẫu của bảng tblBook( bảng lưu các đầu sách)
tblBook
BookCode BookName PublisherCode
B032120449 Introduction to The Design and Analysis of P020202021
Algorithms
B032120450 Operating System Concepts P020202022
Trang 73
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang 74
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Yêu cầu:
1. Thiết kế giao diện sử dụng như trên, chạy script SQL để tạo cơ sở dữ liệu.
2. Hiển thị danh sách các nhà xuất bản lên JTable, viết các sự kiện cho 2 JButton Về trước,
về sau và JTable. Chú ý rằng mỗi lần click vào từng dòng trên JTable thì sẽ hiển thị
thông tin của nhà xuất bản lên phần thông tin chi tiết; Click “Về trước” thì hiển thị nhà
xuất bản ở phía trước; Click “Về sau” thì hiển thị nhà xuất bản ở phía sau.
3. Thực hiện các chức năng Thêm, Lưu, Sửa, Xóa
4. Thực hiện chức năng tìm kiếm khi bấm vào nút “Tìm Kiếm”
Khi thực hiện chức năng này thì giao diện Tìm Kiếm sẽ được hiển thị như bên dưới(chú ý
rằng chức năng này cho phép tìm kiếm tương đối)
Ví dụ: (Khi bấm nút Tìm kiếm trong công cụ tìm kiếm)
Người sử dụng nhập p02, hoặc 23 thì sẽ xuất ra toàn bộ đầu sách theo mã nhà xuất bản có chứa
bất kỳ chuỗi p02, hoặc 23
Gợi ý: Dùng từ khóa like và % trong câu truy vấn tìm kiếm tương đối
Trang 75
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
MODULE 6
Mục đích:
Thực hành về JSP. Module này giúp sinh viên làm quen với Javaservlet và JSP
Thiết kết Html sinh viên có thể sử dụng công cụ Microsoft Expression Web hoặc Dreamweaver
Để tạo Project JSP trong eclipse, chúng ta cần các công cụ sau:
- Chương trình eclipse Java EE
- Apache tomcat ver 7.0 (hoặc tùy …)
- JDK version 6, 7 (hoặc tùy…)
Lab 1: Các bước tạo 1 project Web như sau (sinh viên làm theo lab này trước khi làm các bài tập
bên dưới):
1) Giả sử ta cài tomcat vào “C:\Program Files\Apache Software Foundation\Tomcat 7.0”
Trang 76
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
- Cứ Chọn Next cho tới màn hình cuối cùng và chọn các thông số như hình sau đó
bấm Finish:
Trang 77
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Để kết nối tới SQL Server, chúng ta làm bước sau (trước tiên phải có thư viện kết nối):
- Có nhiều cách tham chiếu tới các thư viện, ở đây chúng ta làm theo cách tham chiếu kiểu
gom nhóm các thư viện vào chung 1 chỗ cho tiện lợi, thực tế chúng ta hay làm theo cách
này:
Bấm chuột phải vào Project/ chọn Build Path / chọn Configure Build Path…
Trang 78
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trong trường hợp này chúng ta sẽ trỏ tới thư viện kết nối Sqlserver, ở đây là gói
sqljdbc4.jar. Chúng ta có thể tìm thấy nó ở bất cứ nơi đâu trên internet.
Trang 80
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bây giờ quan sát Project, chúng ta sẽ thấy thư viện vừa thêm vào:
Để chạy được, chúng ta đồng thời phải sao chép sqljdbc4.jar vào “C:\Program Files\Apache
Software Foundation\Tomcat 7.0\lib”
Ở đây chúng ta sẽ tạo một số class để tương tác tới cơ sở dữ liệu sql server
Class Account là mô hình hóa cơ sở dữ liệu thành hướng đối tượng: ở đây chỉ có mã, tên.
Class MyData có nhiệm vụ truy suất sqlserver và trả về ArrayList Account
Trang 81
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Class Account:
Class MyData:
Tiếp tục, chúng ta tạo 1 trang web, tên là index.jsp để hiển thị danh sách Account:
Trang 82
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang index.jsp:
Sau khi chạy, dữ liệu sẽ được hiển thị lên trang index.jsp như bên dưới.
Trang 83
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang web nào muốn tương tác tới servlet thì làm như sau:
Trang 84
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Thuộc tính action của form chính là tên của servlet, method có 2 loại: Nếu ta chọn “post” thì
hàm doPost của servlet sẽ thực thi, nếu ta chọn “get” thì hàm doGet của servlet sẽ thực thi.
Để lấy các giá trị của các control trên web, chúng ta dùng request.getParameter(“tên”)
- Để triển khai ứng dụng web. Bấm chuột phải vào Project/ Export / WAR file
Tại màn hình này chúng ta Export vào thư mục webapps của apache tom cat.
Muốn chạy : http://localhost:8888/qlthuvien . Với 8888 là port do ta chọn lúc cài đặt.
Trang 85
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Bài tập 1: Quản lý thí sinh, Sinh viên phải làm trên Access và Sqlserver 2008
Cho CSDL có tên QLTS.mdb (sinh viên tự chuyển qua SQL server). Thiết kế bảng Thisinh co
cấu trúc như hình
Tạo 1 ứng dụng Dynamic Web Project có tên QLTS. Thiết kế trang index.jsp sao cho khi chạy
hiển thị danh sách thí sinh như hình sau:
Khi nhấn vào link Insert New sẽ cho phép người dùng nhập thông tin của 1 thí sinh và thêm vào
CSDL như hình:
Trang 86
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Khi nhấn link Edit sẽ cho phép người dùng hiệu chỉnh thông tin của thí sinh được chọn sau đó
cập nhật xuống csdl
Bài tập 2: Quản lý sinh viên. Sinh viên làm theo mẫu Lab này để làm quen với Servlet. Lab này
làm ví dụ cho bài tập 1
- Chương cho phép hiển thị danh sách sinh viên
- Thêm mới sinh viên
- Chỉnh sửa thông tin sinh viên
- Xóa sinh viên
Dưới đây là một phần của thiết kế cơ sở dữ liệu quản lý sinh viên.
Giải thích:
1) Webcontent chứa các tập tin web jsp:
Trang index.jsp sẽ hiển thị danh sách sinh viên theo mẫu bên dưới:
Trang update.jsp/ newpage.jsp: Dùng để chỉnh sửa/ thêm mới sinh viên:
Trang deletepage.jsp : dùng để thực thi việc xóa 1 sinh viên theo mã.
Trang 89
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
2) Trong Java Resource có 4 package thực hiện các chức năng sau:
vn.edu.hui.connector : Dùng để tương tác trực tiếp tới cơ sở dữ liệu (Tạo connection,
tạo Resultset, tạo Statement, update thông tin…)
vn.edu.hui.model : lưu trữ các class là mô hình hóa cơ sở dữ liệu thành hướng đối tượng
vn.edu.hui.dal : Dùng để tương tác với connector, kết hợp chặt chẽ với model.
vn.edu.hui.servlet : Servlet để xử lý các thông tin từ các trang Jsp gửi về.
Trang 90
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
- Package Model
Package dal:
package vn.edu.hui.dal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import vn.edu.hui.connector.ConnectorFactory;
import vn.edu.hui.model.Sinhvien;
public class ProcessSinhvien {
ConnectorFactory factor=null;
public ProcessSinhvien()
{
factor=new ConnectorFactory();
}
public ArrayList<Sinhvien> getList()
{
ResultSet rs=factor.execQuery("select * from sinhvien");
ArrayList<Sinhvien>list=new ArrayList<Sinhvien>();
try {
while(rs.next())
{
Sinhvien sv=new Sinhvien(rs.getString("masinhvien"),
rs.getString("tensinhvien"), rs.getString("malop"));
list.add(sv);
}
} catch (SQLException e) {
e.printStackTrace();
}
Trang 91
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
return list;
}
public Sinhvien getInfor(String masv)
{
Sinhvien sv=null;
try
{
ResultSet rs=factor.execQuery("select * from sinhvien where
masinhvien='"+masv+"'");
rs.next();
sv=new Sinhvien(rs.getString("masinhvien"), rs.getString("tensinhvien"),
rs.getString("malop"));
}
catch(Exception ex)
{
ex.printStackTrace();
}
return sv;
}
public int update(Sinhvien sv)
{
int ret=0;
String sql="update sinhvien set
tensinhvien='"+sv.getTensinhvien()+"',malop='"+sv.getMalop()+"' where
masinhvien='"+sv.getMasinhvien()+"'";
ret=factor.excecNonQuery(sql);
return ret;
}
public int insert(Sinhvien sv)
{
int ret=0;
String sql="insert into sinhvien
values('"+sv.getMasinhvien()+"','"+sv.getTensinhvien()+"','"+sv.getMalop()+"')";
ret=factor.excecNonQuery(sql);
return ret;
}
public int delete(Sinhvien sv)
{
int ret=0;
String sql="delete from sinhvien where masinhvien='"+sv.getMasinhvien()+"'";
ret=factor.excecNonQuery(sql);
return ret;
}
public int delete(String masv)
{
int ret=0;
String sql="delete from sinhvien where masinhvien='"+masv+"'";
ret=factor.excecNonQuery(sql);
return ret;
}
}
Trang 92
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang 93
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Web.xml
Trang 94
http://communityuni.com/ – duythanhcse@gmail.com - https://www.facebook.com/communityuni/
Trang deletepage.jsp:
Trang 95