Professional Documents
Culture Documents
Final Java2 Excercise 2013
Final Java2 Excercise 2013
Lp Trnh Java 2
Khi: i Hc v Cao ng
Nm 2013
Hng dn:
Trang 1
Lp trnh hng i tng vi Java 2
Mc lc
Module 1 : n tp Graphic User Interface..................................................................... 3
Trang 2
Lp trnh hng i tng vi Java 2
MODULE 1
Mc ch:
n tp Graphic User Interface, gip cc sinh vin hiu c LayoutManager, Common Control,
Event, DialogBox, Advanced Control. Sinh vin phi thc hin tt Module 1 ng dng cho
cc Module tip theo, c bit l phn kt ni c s d liu.
Gii thch:
FlowLayout cho php add cc control trn cng mt dng, khi no ht ch cha n s t ng
xung dng, ta cng c th iu chnh hng xut hin ca control. Mc nh khi mt JPanel
c khi to th bn thn lp cha ny s c kiu Layout l FlowLayout.
Hng dn:
BoxLayout cho php add cc control theo dng hoc ct, ti mi v tr add n ch chp nhn 1
control, do mun xut hin nhiu control ti mt v tr th bn nn add v tr l 1 JPanel ri
sau add cc control khc vo JPanel ny.
BoxLayout.X_AXIS : Cho php add cc control theo hng t tri qua phi.
Trang 4
Lp trnh hng i tng vi Java 2
BoxLayout.Y_AXIS : Cho php add cc control theo hng t trn xung di.
Hng dn:
Trang 5
Lp trnh hng i tng vi Java 2
Nu nh khng c 4 vng : North, West, South, East. Th vng Center s trn y ca s, thng
thng khi a cc control JTable, JTree, ListView, JScrollpane ta thng a vo vng
Center n c th t co gin theo kch thc ca s gip giao din p hn.
Trang 6
Lp trnh hng i tng vi Java 2
Hng dn: Sinh vin phi xc nh Layout Manager trc, ta cng c th k hp cc Layout
thit k giao din, t tn control theo yu cu bn di
Trang 7
Lp trnh hng i tng vi Java 2
Khi bm nt Gii th ty thuc vo php ton c chn m kt qu thc hin khc 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("Cng Tr Nhn Chia");
pnNorth.add(lblTitle);
pnBorder.add(pnNorth,BorderLayout.NORTH);
lblTitle.setForeground(Color.BLUE);
Font ft=new Font("arial", Font.BOLD, 25);
lblTitle.setFont(ft);
Trang 8
Lp trnh hng i tng vi Java 2
Border southborder
=BorderFactory.createLineBorder(Color.RED);
TitledBorder southTitleBorder=
new TitledBorder(southborder, "Chn tc v");
pnWest.setBorder(southTitleBorder);
Border centerborder
=BorderFactory.createLineBorder(Color.RED);
TitledBorder centerTitleBorder=
new TitledBorder(centerborder, "nhp 2 s a v b:");
pnCenter.setBorder(centerTitleBorder);
Trang 9
Lp trnh hng i tng vi Java 2
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, "Mun thot
h?", "Thot", JOptionPane.YES_NO_OPTION);
if(ret==JOptionPane.YES_OPTION)
System.exit(0);
}
});
btnXoa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txta.setText("");
txtb.setText("");
Trang 10
Lp trnh hng i tng vi Java 2
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, "Nhp sai
nh dng!");
txta.selectAll();
txta.requestFocus();
return;
}
String sb=txtb.getText();
try
{
b=Integer.parseInt(sb);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Nhp sai
nh dng!");
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
{
kq=a*1.0/b*1.0;
Trang 11
Lp trnh hng i tng vi Java 2
}
txtkq.setText(kq+"");
}
});
Container con=getContentPane();
con.add(pnBorder);
}
public static void main(String[] args) {
CongTruNhanChiaUI ui=new CongTruNhanChiaUI("Cng - Tr - Nhn -
Chia");
ui.doShow();
}
}
- Chng trnh cho php nhp vo cc s nguyn t giao din trong phn nhp thng tin,
Khi ngi s nhp gi tr vo JTextField v click nt Nhp th s cp nhp d liu
xung JList, Nu checked vo Cho nhp s m th cc s m mi c php a vo
JList cn khng th thng bo li.
- Chn tc v, sinh vin phi thc hin ton b cc yu cu
- Nt ng chng trnh: s hin th thng bo hi ngi s dng c mun ng hay
khng.
Trang 12
Lp trnh hng i tng vi Java 2
o Lu i tng:
public static void luuDoiTuong(Object obj, String fileName)
{
try
{
FileOutputStream fOut=new FileOutputStream(fileName);
ObjectOutputStream out=new ObjectOutputStream(fOut);
out.writeObject(obj);
out.close();
Trang 13
Lp trnh hng i tng vi Java 2
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
o c i tng
public static Object docDoiTuong(String fileName)
{
try
{
FileInputStream fIn=new FileInputStream(fileName);
ObjectInputStream in=new ObjectInputStream(fIn);
Object o=in.readObject();
in.close();
return o;
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
- Trong testMain:
DanhMucSanPham dsDienTu=(DanhMucSanPham )MyFile.docDoiTuong("luuluu.data");
if(dsDienTu!=null)
System.out.println(dsDienTu);
MyFile.luuDoiTuong(dsDienTu, "luuluu.data");
Bi tp 9: Thc hnh v Timer class (*)
Giao din s c 2 JButton: Start v Stop. Khi bm Start chng trnh s hin th hnh nh tun t
trong mng 10 hnh nh c sn. Bm Stop tm dng duyt hnh nh. Xem hnh yu cu
Trang 14
Lp trnh hng i tng vi Java 2
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
Lp trnh hng i tng vi Java 2
Bi tp 10: Ci tin bi tp 10. Chng trnh s cho php c danh sch cc hnh nh bt k
trong a. (*)
Hng dn:
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());
JPanel pnNorth=new JPanel();
Trang 17
Lp trnh hng i tng vi Java 2
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();
{
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();
}
}
Bi tp 11: Thc hnh v to Menu. Yu cu thit k Menu theo hnh sau, ng vi mi menu
item sinh vin hy ci t coding hin th thng bo l ang chn menu no. (*)
Trang 19
Lp trnh hng i tng vi Java 2
package baitap13;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Trang 20
Lp trnh hng i tng vi Java 2
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
Lp trnh hng i tng vi Java 2
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
Lp trnh hng i tng vi Java 2
MODULE 2
Mc ch:
Thc hnh MultiThreading, hiu c Thread, Runnable, Swings vi Threading
Trang 23
Lp trnh hng i tng vi Java 2
Trang 24
Lp trnh hng i tng vi Java 2
Trang 25
Lp trnh hng i tng vi Java 2
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
Lp trnh hng i tng vi Java 2
/**
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
@param max the maximum amount of money in each transfer
Trang 27
Lp trnh hng i tng vi Java 2
*/
public TransferRunnable(Bank b, int from, double max)
{
bank = b;
fromAccount = from;
maxAmount = max;
}
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;
}
Chng ta sa li hm run :
Kt qu l gi liu c ng b
Class Bank
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
Trang 29
Lp trnh hng i tng vi Java 2
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()
{
bankLock.lock();
try
{
double sum = 0;
Trang 30
Lp trnh hng i tng vi Java 2
sum += a;
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;
}
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();
}
}
Bi tp 9: Dng a tin trnh cp nhp d liu cho JProgressBar. Giao din chng trnh nh
bn di.
Trang 32
Lp trnh hng i tng vi Java 2
Coding mu :
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);
}
}
Bi tp 10: Dng a tin trnh minh ha cc thut ton sp xp nh giao din bn di: (*)
Trang 33
Lp trnh hng i tng vi Java 2
MODULE 3
Mc ch:
Thc hnh v Collections, gip sinh vin hiu c : ArrayList, LinkedList, Vector, Hash table,
HashSet, LinkedHashSet, TreeSet, HashMap, TreeMap, PriorityQueue, Properties.
Bi tp 1 : Vit chng trnh qun l sinh vin di dng console, yu cu s dng ArrayList
hoc LinkedList hoc Vector v thc hin cc chc nng sau (thng tin sinh vin bao gm : m
s sinh vin, h tn, nm sinh, a ch, lp hc):
a) Cho php thm, sa, xa danh sch sinh vin
b) Xut ra s lng sinh vin
c) Xut ra danh sch cc sinh vin thuc mt lp hc bt k nhp vo t bn phm
d) Cho php lu/m danh sch sinh vin trn cng
Trang 34
Lp trnh hng i tng vi Java 2
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;
}
public boolean addSinhvien(Sinhvien sv)
{
if(ktTrungma(sv.getMasv()))
Trang 35
Lp trnh hng i tng vi Java 2
return false;
return dsSv.add(sv);
}
public Sinhvien findSinhvien1(String masv)
{
for(Sinhvien sv : dsSv)
{
if(sv.getMasv().equalsIgnoreCase(masv))
return sv;
}
return null;
}
public int findSinhvien2(String masv)
{
for(int i=0;i<dsSv.size();i++)
{
if(dsSv.get(i).getMasv().equalsIgnoreCase(masv))
return i;
}
return -1;
}
public Sinhvien updateSinhvien(int index,Sinhvien sv)
{
return dsSv.set(index, sv);
}
public void removeSinhvien(String masv)
{
Sinhvien sv=findSinhvien1(masv);
dsSv.remove(sv);
//int pos=findSinhvien2(masv);
//dsSv.remove(pos);
}
public String toString() {
return dsSv.toString();
}
}
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("Nguyn Vn To");
qlsv.addSinhvien(teo);
Sinhvien ty=new Sinhvien();
ty.setMasv("114");
ty.setTensv("Nguyn Th t");
qlsv.addSinhvien(ty);
System.out.println(qlsv);
}
Trang 36
Lp trnh hng i tng vi Java 2
if(Masv.equalsIgnoreCase(o.getMasv()))
return 0;
return 1;
}
package chap2.quanlysinhvien;
import java.util.ArrayList;
import java.util.Collections;
}
Khi no mun sp xp danh sch chng ta ch cn gi hm sort trong class trn.
public class TestSinhvien {
public static void main(String[] args) {
DanhSachSinhvien qlsv=new DanhSachSinhvien();
Sinhvien teo=new Sinhvien();
teo.setMasv("113");
teo.setTensv("Nguyn Vn To");
qlsv.addSinhvien(teo);
Sinhvien ty=new Sinhvien();
ty.setMasv("114");
ty.setTensv("Nguyn Th t");
qlsv.addSinhvien(ty);
qlsv.sort();
System.out.println(qlsv);
}
Bi tp 3: Hiu chnh bi tp 1 v dng Graphic User Interface, giao din nh bn di:
Trang 37
Lp trnh hng i tng vi Java 2
Yu cu:
- S dng SimpleDateFormat nh dng nhp nm sinh.
- Nt Thm cho php xa trng d liu mc thng tin chi tit v cho php nhp d liu
mi vo, khi nhp nt Lu s lu thng tin xung ArrayList ng thi cp nhp JTable.
- Nt Lu dng lu sinh vin vo danh sch ArrayList, nu m tn ti th t ng gi
hm cp nhp thng tin.
- Nt xa cho php xa sinh vin ang chn trong JTable.
- Mi ln click vo tng dng trong JTable th s hin th thng tin chi tit ca sinh vin
vo phn thng tin chi tit.
- Nt Lu tp tin cho php lu danh sch sinh vin xung cng (map i tng)
- Nt M tp tin cho php load danh sch sinh vin trong tp tin ln JTable
- Nt thot : khi no ngi s dng chn nt ny th s hin th thng bo hi ngi s
dng c chc chn mun thot hay khng? Nu mun thot th s ng chng trnh, nu
khng th gi nguyn mn hnh.
*** Ch , nhng bi ny l tin vo chng JDBC chng ta s tip tc s dng
li, do sinh vin phi hiu cch to giao din, gn s kin cng nh cch s dng cc
collections.
Coding mu cho phn giao din (phn x l thng tin sinh vin t thc hin):
package chap2.quanlysinhvien;
Trang 38
Lp trnh hng i tng vi Java 2
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(Color.BLUE),
"Thng tin chi tit"));
pnNorth.add(pnDetail);
Trang 39
Lp trnh hng i tng vi Java 2
pnTable.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLUE),
"Danh sch sinh vin"));
model=new DefaultTableModel();
model.addColumn("M");
model.addColumn("Tn");
model.addColumn("Nm sinh");
model.addColumn("a ch");
model.addColumn("Lp");
pnButton2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.RED),
"Nhp xut"));
btnMotaptin =new JButton("M tp tin");
pnIo.add(btnMotaptin);
btnLuutaptin=new JButton("Lu tp 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("Qun l sinh vin");
ui.doShow();
}
}
package chap1.myHashTable;
public class Person {
private String Id;
private String Name;
public String getId() {
return Id;
Trang 41
Lp trnh hng i tng vi Java 2
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public Person(String id, String name) {
super();
Id = id;
Name = name;
}
public String toString() {
return "Person [Id=" + Id + ", Name=" + Name + "]";
}
}
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);
}
}
}
Bi tp 5: Sinh vin hiu chnh bi tp 3, thay v s dng ArrayList qun l danh sch sinh
vin, by gi chng ta phi s dng Hashtable qun l nhn s (dng class Person bi 4).
Trang 42
Lp trnh hng i tng vi Java 2
package chap2.myHashSet;
package chap2.myHashSet;
import java.util.HashSet;
import java.util.Iterator;
Trang 43
Lp trnh hng i tng vi Java 2
}
}
Trang 44
Lp trnh hng i tng vi Java 2
Bi tp 11: Ci tin bi tp 10
Hy s dng PriorityQueue qun l u tin v phc tp ca cng vic.
- Nu cng vic no c u tin ln hn th c thc hin trc
- Nu cng vic no c cng u tin th tnh theo phc tp, cng vic no c phc
tp nhiu nht th c thc hin trc.
Trang 45
Lp trnh hng i tng vi Java 2
MODULE 4
Mc ch:
Thc hnh v Networking. Module ny gip sinh vin hiu c v InetAddress, Socket, RMI
SOCKET PROGRAMMING
Bi tp 1:
Vit 1 chng trnh c tn Calculator_server nhn 1 biu thc gm 2 ch s v 1 php ton sau
thc thi biu thc ny v gi kt qu li cho client.
Sa cha chng trnh cho php nhiu client kt ni cng lc.
Pha client, vit giao din gm 2 JtextField cho vic nhp s, 1 JLabel cho vic xut kt qu.
Cc nt Cng, tr, nhn,chia, clear v thot.
Giao din cho client nh sau:
Bi tp 2:
Vit chng trnh gii phng trnh bc 2, server lng nghe ti port 8189, cho php chy nhiu
client. Yu cu vit theo 3 trng hp (dng Text Stream, Data Stream, Object Stream) Giao
din c cho nh bn di:
- Khi chn nt Thot, chng trnh s hi ngi s dng c mun thot hay khng.
Trang 46
Lp trnh hng i tng vi Java 2
Trang 47
Lp trnh hng i tng vi Java 2
@Override
public void run()
{
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()
{
Trang 48
Lp trnh hng i tng vi Java 2
createUI();
}
private void createUI()
{
setLayout(new BorderLayout());
JPanel pnNorth=new JPanel();
pnNorth.setBackground(Color.CYAN);
JLabel lblNorth=new JLabel("Gii Phng Trnh Bc 2");
pnNorth.add(lblNorth);
Container con=getContentPane();
con.add(pnNorth,BorderLayout.NORTH);
Trang 49
Lp trnh hng i tng vi Java 2
pnButton.add(btnClear);
pnButton.add(btnExit);
pnInfor.add(pnButton);
}
private void clearText()
{
txta.setText("");
txtb.setText("");
txtc.setText("");
}
private void proccessInformation()
{
try
{
Socket soc=new Socket("localhost",8189);
//Send Information to server
OutputStream out=soc.getOutputStream();
PrintWriter printOut=new PrintWriter(out,true);
printOut.println(Double.parseDouble(txta.getText()));
printOut.println(Double.parseDouble(txtb.getText()));
printOut.println(Double.parseDouble(txtc.getText()));
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);
}
}
Trang 50
Lp trnh hng i tng vi Java 2
}
/**w
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
CClientPtb2TextStream client=new CClientPtb2TextStream();
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.setSize(400, 300);
client.setVisible(true);
}
package duythanhwordpress.com.chapter3.ptb2textstream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Trang 51
Lp trnh hng i tng vi Java 2
Ti y Sinh vin chy class Test Server (CServerPtb2TextStream) trc, sau chy class
Test Client (CClientPtb2TextStream)
Bn 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());
}
}
Bn 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();
}
Trang 52
Lp trnh hng i tng vi Java 2
}
Vi processInformation l hm x l gii phng trnh bc 2, tr v kt qu sau khi nhn thng
s t client gi ln (Sinh vin t vit thut ton gii pt bc 2 trong hm ny).
Bn 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();
}
}
Bn 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)
{
Trang 53
Lp trnh hng i tng vi Java 2
ex.printStackTrace();
}
}
Class CPTB2
package duythanhwordpress.com.chapter3.ptb2objectstream;
import java.io.Serializable;
Trang 54
Lp trnh hng i tng vi Java 2
}
public String getKetQua()
{
return this.m_strKetQua;
}
}
Bi tp 3:
Vit 1 server cho php nhiu client kt ni cng lc vi cc yu cu sau:
Client c th gi yu cu l ng dn n 1 i hoc 1 th mc no bt k trn server.
Nu ng dn tn ti th s gi v danh sch cc th mc con v cc tp tin trong a /
ng dn .
Thit k client vi c ch GUI nhn kt qu t server v biu din kt qu nhn c ln 1
JTree.
Hng dn:
on code sau lit k tt c th mc, tp tin trong 1 ng dn path cho trc ri a vo 1 i
tng 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
Lp trnh hng i tng vi Java 2
Bi tp 4:
Bi tp 5:
Vit 1 chng trnh t in cho php tra t qua mng. VIc tra t ny phi m bo nhiu ngi
c th tra cng lc. Vic thit k chng trnh gm 2 phn: Phn server v phn client.
Phn server: ch s c chy trn server c giao din nh sau:
Trang 56
Lp trnh hng i tng vi Java 2
Khi ngi dng start server t in, server ny s lng nghe trn cng 2520 v s nhn u vo
l t cn tra sau thc hin vic tra t v tr kt qu v cho client hoc l 1 i tng t tra
trong trng hp tra thnh cng, hoc l null nu t khng tn ti.
Phn Client: s c trin khai pha client, c giao din nh sau
Trang 57
Lp trnh hng i tng vi Java 2
Bi tp 6:
Vit chng trnh to ra mt bn phm trn 2 my tnh A v B. vit chng trnh iu khin cc
s kin nhn phm trn my tnh B thng qua my tnh A v hin kt qu ln mn hnh ca my
B( th d: khi nhn mt phm trn my A cng tng ng vi vic nhn phm trn my tnh
B)
Bi tp 7:
Vit chng trnh gi lp 1 chat room. Ngi dng nhp a ch server, tn nick chat vo v c
th chat cng nhau trn chat room ny.
Trang 58
Lp trnh hng i tng vi Java 2
UDP PROGRAMMING
Bi tp 1:
Vit 1 chng trnh lm server s dng UDP cho php lng nghe trn cng 2520. Khi client gi
yu cu n th server ny s gi 1 file hnh nh v client. pha client, sau khi nhn c
image t server th lu image ny xung file ng thi hin th ln 1 JFrame.
Bi tp 2:
Vit chng trnh lm server s dng UDP cho php lng nghe trn cng 7777. Khi client gi
yu cu n th server ny s gi 1 file audio/video v client. pha client, sau khi nhn c
file audio/video t server s lu file ny xung a v cho thc thi file va nhn c.
Coding mu:
Server:
Trang 59
Lp trnh hng i tng vi Java 2
Client:
- Khi bm vo Start, chng trnh s khi ng server ti port c nhp trn giao din.
- Khi bm Stop, s thot chng trnh
Thit k giao din client nh bn di, cho php ngi s dng chn tp tin trn server
download (hnh nh), sau hin th ln giao din:
Trang 60
Lp trnh hng i tng vi Java 2
- Ch l chng trnh cho php chy ng thi nhiu client truy sut ln server (kt hp
Multithreading + Networking).
- Bn phi mn hnh c JList, khi ngi s dng bm vo nt Get Files th chng trnh c
nhim v ln server ly ton ng dn cc tp tin nm trong Server Path.
- Khi bm vo nt Download, chng trnh s dng UDP ti tp tin ang chn trong JList,
lu v my client vi tn mi c nhp trong New File Name. Sau khi ti xong tp tin
th t ng m tp tin ny ln giao din (nhn bn tri mn hnh).
- Khi c li sy ra th chng trnh phi hin th thng bo li, tng t nh thng bo li
di y :
RMI PROGRAMMING
Cc bc to ng dng RMI (4 bc):
Trang 61
Lp trnh hng i tng vi Java 2
Bi tp 1:
Vit chng trnh dng k thut RMI cho vic chuyn i tin t. Chng trnh cho php nhp
vo s tin, chn loi tin (USD/VND) ri tnh ton. Giao din client nh sau:
Trang 62
Lp trnh hng i tng vi Java 2
Bi tp 2:
Vit chng trnh dng k thut RMI cho vic tnh ton cc s vi cc php tnh c bn. Client
s dng c ch ha nh sau:
Bi tp 3:
Vit chng trnh bi online, kt hp chuyn lch m thnh lch dng. Giao din Server nh
sau:
- Nhim v ca Server l nhn 3 thng s: ngy, thng, nm t client v tin hnh gii m
- Khi bm Start Server, chng trnh s ng k RMI object ng nh thng s trn giao
din m ngi s dng nhp, chui URL t ng c ni khi bm Start thnh cng.
- Khi bm Shutdown, chng trnh s tt.
Trang 63
Lp trnh hng i tng vi Java 2
Bi tp 4: Dng k thut RMI vit chng trnh gii phng trnh bc 2, giao din nh sau:
Trang 64
Lp trnh hng i tng vi Java 2
MODULE 5
Mc ch:
Thc hnh v JDBC, Module ny gip sinh vin kt ni ti Ms Access, SQL Server, MySQL.
Thc hin c cc chc nng : ly d liu, thm, sa , xa... C th ng dng vit cc
chng trnh qun l.
V d v kt ni vi nhiu h c s d liu, sinh vin xem trn blog ny :
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
Lp trnh hng i tng vi Java 2
Bi tp 1:
Lm cc demontraction v kt ni CSDL v thc thi cc phong thc ca i tong
Statement,PrepareStatement:
-executeQuery
- executeUpdate
- executeBatch
Bi tp 2: Thao tc trn ResultSet
Cho c s d liu tn l QLSV vi cu trc bng oc cho nh sau:
Trang 66
Lp trnh hng i tng vi Java 2
Nhn Hy hoc lu, sau khi thc hin xong tcc v s khi phc giao din tr li nh ban u.
Khi nhn nt Sa
Khi nhn nt Xem danh sch sinh vin lp hin ti, 1 ca s nh sau xut hin hin th cc sinh
vin thuc lp hin ti ang c chn
Trang 67
Lp trnh hng i tng vi Java 2
Trang 68
Lp trnh hng i tng vi Java 2
To c s d liu theo m hnh trn trn h qun tr CSDL Access hoc SQL server 2008.
To form logon nh hnh sau:
Khi user nhn nt logon, chng trnh s kim tra user v password ri hin th thng bo chnh
xc cn thit nu user khng ng nhp c.
Nu user ng nhp thnh cng, chng trnh s lu tr 1 mu tin xung bng tblSession ng
thi ly v tt c cc quyn m user ang c trn bng tblPrivileges.
Khi hin th chng trnh chnh. Ty theo quyn m user ang c, cc menu ca chng trnh
chnh s c enable hoc disable.
Hy to cc form qun l users. Cc chc nng thm,xa, sa, cp nht, tm kim,chc
nng cp quyn cho users.
Trang 69
Lp trnh hng i tng vi Java 2
Form i password
Trang 71
Lp trnh hng i tng vi Java 2
o
o Khi bm nt Remove bn Danh mc sn phm, chng trnh s xa danh mc sn
phm ang chn. Ch rng nu Danh mc ny c sn phm bn trong th phi
thng bo cho ngi s dng bit v hi xem c mun xa tt c lun hay khng.
o Khi bm nt New bn phn sn phm: xa trng cc JTextField, cho php ngi
s dng nhp mi 1 sn phm theo tng danh mc
o Khi bm nt Save: chng trnh s lu thng tin ca sn phm, Nu nh m tn
ti th t ng update, cn m cha tn ti th thc hin lu mi sn phm.
o Khi bm nt Remove bn phn sn phm: chng trnh s xa sn phm ang
chn trong JTable.
o Menu File: S c 2 mc menu con; Menu 1 tn l Print cho php in n ton b
danh mc sn phm v cc sn phm bn trong danh mc. Menu 2 tn l Exit, cho
php thot khi chng trnh.
- in n chng ta implements Printable, sinh vin c nhim v tm hiu chc nng in n
trn internet.
- hin th thng bo hi ngi s dng c chc chn mun thot hay khng, ta dng
on code di y:
if(JOptionPane.showConfirmDialog
(this, "Bn c chc chn mun thot khng?","Thngbo",
JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
System.exit(0);
Trang 72
Lp trnh hng i tng vi Java 2
D liu mu:
D liu mu ca bng tblPublisher( bng nh xut bn)
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
Trang 74
Lp trnh hng i tng vi Java 2
Yu cu:
1. Thit k giao din s dng nh trn, chy script SQL to c s d liu.
2. Hin th danh sch cc nh xut bn ln JTable, vit cc s kin cho 2 JButton V trc,
v sau v JTable. Ch rng mi ln click vo tng dng trn JTable th s hin th thng
tin ca nh xut bn ln phn thng tin chi tit; Click V trc th hin th nh xut bn
pha trc; Click V sau th hin th nh xut bn pha sau.
3. Thc hin cc chc nng Thm, Lu, Sa, Xa
4. Thc hin chc nng tm kim khi bm vo nt Tm Kim
Khi thc hin chc nng ny th giao din Tm Kim s c hin th nh bn di(ch
rng chc nng ny cho php tm kim tng i)
Trang 75
Lp trnh hng i tng vi Java 2
Trang 76
Lp trnh hng i tng vi Java 2
MODULE 6
Mc ch:
Thc hnh v JSP. Module ny gip sinh vin lm quen vi Javaservlet v JSP
Thit kt Html sinh vin c th s dng cng c Microsoft Expression Web hoc Dreamweaver
to Project JSP trong eclipse, chng ta cn cc cng c sau:
- Chng trnh eclipse Java EE
- Apache tomcat ver 7.0 (hoc ty )
- JDK version 6, 7 (hoc ty)
Lab 1: Cc bc to 1 project Web nh sau (sinh vin lm theo lab ny trc khi lm cc bi tp
bn di):
1) Gi s ta ci tomcat vo C:\Program Files\Apache Software Foundation\Tomcat 7.0
Bm chut phi vo
Project Explorer /
new/ chn Dynamic
Web Project
Trang 77
Lp trnh hng i tng vi Java 2
- C Chn Next cho ti mn hnh cui cng v chn cc thng s nh hnh sau
bm Finish:
Trang 78
Lp trnh hng i tng vi Java 2
Bm chut phi vo Project/ chn Build Path / chn Configure Build Path
Trang 79
Lp trnh hng i tng vi Java 2
Trang 80
Lp trnh hng i tng vi Java 2
Trang 82
Lp trnh hng i tng vi Java 2
Class MyData:
Tip tc, chng ta to 1 trang web, tn l index.jsp hin th danh sch Account:
Trang index.jsp:
Trang 83
Lp trnh hng i tng vi Java 2
Trang 84
Lp trnh hng i tng vi Java 2
Thuc tnh action ca form chnh l tn ca servlet, method c 2 loi: Nu ta chn post th
hm doPost ca servlet s thc thi, nu ta chn get th hm doGet ca servlet s thc thi.
Trang 85
Lp trnh hng i tng vi Java 2
- trin khai ng dng web. Bm chut phi vo Project/ Export / WAR file
Trang 86
Lp trnh hng i tng vi Java 2
Cho CSDL c tn QLTS.mdb (sinh vin t chuyn qua SQL server). Thit k bng Thisinh co
cu trc nh hnh
To 1 ng dng Dynamic Web Project c tn QLTS. Thit k trang index.jsp sao cho khi chy
hin th danh sch th sinh nh hnh sau:
Khi nhn vo link Insert New s cho php ngi dng nhp thng tin ca 1 th sinh v thm vo
CSDL nh hnh:
Trang 87
Lp trnh hng i tng vi Java 2
Khi nhn link Edit s cho php ngi dng hiu chnh thng tin ca th sinh c chn sau
cp nht xung csdl
Bi tp 2: Qun l sinh vin. Sinh vin lm theo mu Lab ny lm quen vi Servlet. Lab ny
lm v d cho bi tp 1
- Chng cho php hin th danh sch sinh vin
- Thm mi sinh vin
- Chnh sa thng tin sinh vin
- Xa sinh vin
Trang 89
Lp trnh hng i tng vi Java 2
Gii thch:
1) Webcontent cha cc tp tin web jsp:
Trang index.jsp s hin th danh sch sinh vin theo mu bn di:
Trang 90
Lp trnh hng i tng vi Java 2
Trang 91
Lp trnh hng i tng vi Java 2
- 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();
}
return list;
Trang 92
Lp trnh hng i tng vi Java 2
}
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 93
Lp trnh hng i tng vi Java 2
Trang 94
Lp trnh hng i tng vi Java 2
Web.xml
Trang 95
Lp trnh hng i tng vi Java 2
Trang deletepage.jsp:
Trang 96