You are on page 1of 51

MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Trang 1
TRNG I HC KHOA HC T NHIN
KHOA CNG NGH THNG TIN
B MN CNG NGH PHN MM


Xy Dng Phn Mm
Hng i Tng
N MN
Tn n : MVC Architecture
& Struts Framework In
Java(J2EE)
GVHD : Trn Minh Trit
SV thc hin :
V c Thin (06hc418)
Nguyn Tr Ton (06hc425)
Nguyn Thnh Trc (06hc437)
Thng 10/2007
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Mc Lc

Phn I : Tng quan ngn ng java.........................................................................4
1. Lch s pht trin ca Java.............................................................................4
2. Mc ch ca Java .........................................................................................4
3. c im ca Java ........................................................................................4
4. Cc loi chng trnh trong java ...................................................................5
5. Cc thnh phn ca Java Environment ..........................................................5
6. Cc loi ng dng java .................................................................................5
Phn II : Mi Trng Pht Trin ng Dng Java..............................................6
1. Khi nim ......................................................................................................6
2. Kin trc Eclipse............................................................................................6
3. The Platform runtime.....................................................................................7
4. The workspace ...............................................................................................7
5. The Workbench..............................................................................................7
6. Team support .................................................................................................7
7. Help ...............................................................................................................7
Phn III : Gii thiu J2EE v cc thnh phn lin quan.....................................8
1. Applet.............................................................................................................8
2. JavaBean ........................................................................................................9
3. JSP............................................................................................................... 10
4. Servlets...........................................................................................................11
Phn IV : Kin trc MVC (Model _View_Controller).........................................13
1. Khi nim.......................................................................................................13
2. Mi quan h gia View v controller ............................................................14
3. Mi quan h gia Model v view..................................................................14
4. Cc li im ca MVC..................................................................................15
5. Hn ch ca MVC..........................................................................................15
Phn V : p dng kin trc MVC xy dng ng dng trin khai thc t.........16
1. Qui trnh thc hin ........................................................................................16
1.1. View .................................................................................................16
1.2. Controller .........................................................................................17
1.3. Model ................................................................................................20
2. Trin khai ng dng ......................................................................................23
2.1. C s d liu.....................................................................................23
2.2. B tr cc tp tin trn Eclipse............................................................23
2.3. Kt qu..............................................................................................24
Phn VI : Struts Framework .................................................................................25
1. Struts 1.0 ..........................................................................................................25
1.1. Khi nim................................................................................................25
1.2. Cu trc ca Struts..................................................................................26
1.3. Cc thnh phn chnh ca mt ng dng Struts .....................................27
1.4. Cc file cu hnh cn thit xy dng mt ng dng Struts ................27
1.5. u im ca Struts (so vi MVC s dng RequestDispatcher) .............28
1.6. Nhc im ca Struts............................................................................28
2. Struts 2.0 ..........................................................................................................29




Trang 2
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Phn VI: p dng kin trc MVC xy dng ng dng trin khai thc t ........30
1. Qui trnh thc hin...........................................................................................30
1.1. Cc trang hin th(View)......................................................................30
1.2.Action....................................................................................................37
1.3.Bean ......................................................................................................40
1.4.Utils ......................................................................................................46
1.5.Struts.xml ..............................................................................................47
1.6.Build.xml ..............................................................................................49
2 . Trin Khai ng Dng.....................................................................................50
2.1.C s d liu.........................................................................................50
2.2. B tr cc tp tin trn Eclipse..............................................................50



Website Tham Kho


www.vietcore.net

www.javavietnam.org

www.sun.java.com

www.apache.com

www.manguon.com



Trang 3
MVC Architecture & Struts Framework in J2EE (Java) 10/2007


Phn I
Tng quan ngn ng java


1. Lch s pht trin ca Java
Ra i ti Sun Microsystems bi James Gosling
1991: Version u tin vi tn Oak
1995: Tn chnh thc l Java

2. Mc ch ca Java:
Dng pht trin ng dng cho cc thit b in t thng minh
To cc trang web c ni dung ng (web applet)
Hin nay, Java c s dng pht trin nhiu loi ng dng khc
nhau: c s d liu, mng, Internet, vin thng...

3. c im ca Java :
Ging C/C++
n gin
Object-oriented, hng i tng
Platform-independent, khng ph thuc nn
Mnh
Secure, bo mt
Distributed, phn b
Multithreaded, x l a lung
Dynamic, ng

Chng trnh dch c in


















Trang 4
MVC Architecture & Struts Framework in J2EE (Java) 10/2007







Chng trnh dch trong java















4. Cc loi chng trnh trong java :
Applets
Command Line Applications
GUI Applications
Servlets
Database Applications

5. Cc thnh phn ca Java Environment
Java language
Bytecode definitions
Java/Sun class libraries
Java Virtual Machine
Structure of .class files

6. Cc loi ng dng java :
J2SE : Java 2 Standard Edition (Dng pht trin cc ng dng va v nh)
J2EE : Java 2 Enterprise Edition (Dng pht trin cc ng dng ln)
J2ME : Java 2 Micro Edition (Dng pht trin cc ng dng trn tdd)









Trang 5
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Phn II
Mi Trng Pht Trin ng Dng Java



1. Khi nim :
Eclipse l phn mm min ph, c cc nh pht trin s dng xy dng
nhng ng dng J2EE, s dng Eclipse nh pht trin c th tch hp vi nhiu
cng c h tr khc c c mt b cng c han chnh m khng cn dng
n phn mm ring no khc.Eclipse SDK bao gm 3 phn chnh : Platform,
Java Development Toolkit (JDT), Plug-in Development Environment (PDE).
Vi JDT, Eclipse c xem nh l mt mi trng h tr pht trin Java mnh
m. PDE h tr vic m rng Eclipse, tch hp cc Plug-in vo Eclipse Platform.
Eclipse Platform l nn tng ca ton b phn mm Eclipse, mc ch ca n l
cung cp nhng dch v cn thit cho vic tch hp nhng b cng c pht trin
phn mm khch di dng Plug-in, bn thn JDT cng c th c coi nh l
mt Plug-in lm cho Eclipse nh l mt Java IDE (Integrated Development
Enviroment).

2. Kin trc Eclipse :



Trang 6
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

3. The Platform runtime :
Cng vic chnh ca Platform runtime l pht xem plug-in no ang c
trong th mc plug-in ca Eclipse.Mi Plug-in u c 1 tp tin Manifest lit
k nhng kt ni m plug-in cn.Pug-in ch c ti vo Eclipse mi khi
thc s cn thit gim lng ti nguyn yu cu v thi gian khi to.

4. The workspace :
Workspace chu trch nhim qun l ti nguyn ngi dng c t chc
di dng Project. Mi Project l mt th mc con trong th mc
Workspace.
Workspace bo qun cp thp lch s nhng s thay i ti nguyn, trnh
tht thot ti nguyn ngi dng.
Workspace ng thi chu trch nhim thng bo nhng cng c cn thit
cho vic thay i ti nguyn.

5. The Workbench :
Workbench l giao din ha ngi dng ca Eclipse, gm c Standard
Widget Toolkit (SWT) v JFace. Eclipse khng han ton bt buc phi s
dng SWT hay Jface lp trnh giao din, bn vn c th s dng AWT
hay SWING ca Java thng qua vic ci t cc Plug-ins.

6. Team support :
Trang b h thng qun tr qun l d n ca ngi dng : Concurrent
Versions System (CVS).

7. Help :
Cung cp h thng ti liu m rng, c th l nh dng HTML hay XML.

Ca s chnh ca eclipse3.2



Trang 7
MVC Architecture & Struts Framework in J2EE (Java) 10/2007


Phn III
Gii thiu J2EE v cc thnh phn lin quan
(Applet , JavaBean , JSP , Servlet , EJB)

L 1 thnh phn rt quan trng v rng ln trong lnh vc java , J2EE c
dng pht trin cc ng dng ln mang tnh cht phn tn rng khp. y
l lnh vc c ch trng v ng dng nhiu nht ca java trong thc t.

S cc thnh phn trong J2EE



1. Applet :

l mt chng trnh Java chy trn web browser
Tt c cc applets phi l lp con ca lp Applet hoc JApplet
to ra mt applet, ta phi import:
java.applet
java.awt
Mt applet c 4 phng thc. Mi phng thc c t ng gi khi c
event tng ng.
Methods:
init( )
start( )
stop( )
destroy( )

Trang 8
MVC Architecture & Struts Framework in J2EE (Java) 10/2007


S khc nhau gia Applet v Application
Applications chy bng Java interpreter, cn applets chy trn browser c h
tr Java, hoc dng AppletViewer c trong JDK.
Vic thc hin mt applications bt u trong hm main(). Cn applet th
khng cn hm main.
Applications dng System.out.println() xut, trong khi applets dng hm
drawString() hin th.

Cc hn ch v Security trn Applets
Khng th c hoc vit cc file trn h thng file ca user.
Khng th trao i vi mt site trn.
Khng th chy c cc chng trnh trn h thng hin hnh
Khng th ti bt k chng trnh c lu tr trn h thng ca user.


2. JavaBean:



JavaBeans l software component model
N c th tng tc vi cc i tng ca cc software khc v c th c
dng li
Cc software components m c th dng li ny c gi l beans
Components c dng trong distributed environments. JavaBeans c thit
k dng khi cn.
Java thng xy dng cc software thng qua cc JavaBeans.
Khi m Java Beans c to ra, th chng c th c dng nh mt th vin
khng ph thuc nn


Trang 9
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Cc qui tc to ra mt Beans
L mt class.
phi c mt default constructor.
C t nht mt thuc tnh v l non-public
Cc thuc tnh c truy xut t bn ngoi thng qua cc hm getXXX v
setXXX.


3. JSP : (Java Server Pages)
JSP technology c xy dng trn ngn ng lap trnh Java
No tha ke tat ca cac u iem cng nh cac ac tnh cua ngn ng Java.
JSP co the dung trn tat ca cac platforms

Cch lm vic ca JSP





Cc bc x l ca 1 request





Trang 10
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Cu trc ca trang JSP :
Cc th lnhHTML.
M lnh Java. C 3 thnh phn chnh:
o Directives
o Scripting Elements
o Actions


C ch hot ng ca JSP






4. Servlets :

Lch s ca Web Application



Servlets c dng m rng cc chc nng ca Java-enabled server
Dng thay th cho CGI Scripts
Trc servlets, chung ta co cac cng nghev e tao ra web applications:
Common Gateway Interface (CGI)
FastCGI
ASP
Server-side Java Script
Chay trong Java Virtual Machine
Khng bat buoc Web browser phai ho tr Java

c im Servels :
Khng phu thuoc nen
Lam viec trn nhieu web servers

Trang 11
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
La cng nghe au tin cua java e tao ra web Application
Khng nam trong core Java API ma nam trong hai package
javax.servlet va javax.servlet.http cua Java Servlet Development Kit
(JSDK)


Kin trc Servlets





Vng i ca 1 Servlet



Cu trc ca 1 Servlet:
L lp con ca lp HttpServlet
Override phng thc doGet v doPost nu cn. Hai phng thc ny
u nhn vo hai tham s HttpServletRequest v HttpServletResponse.
Hai phng thc ny u nm ra IOException v ServletException




Trang 12
MVC Architecture & Struts Framework in J2EE (Java) 10/2007


Phn IV
Kin trc MVC (Model _View_Controller)





1. Khi nim :
M hnh Model-View-Controller chia cc components ca ng dng thnh 3 loi
khc nhau l Model (mu), View (hin th), v Controller iu khin). Cc
components ca m hnh MVC m nhn mt trch nhim nht nh v mi
components u c lp vi cc components khc. Vic thay i 1 components s
khng nh hng hoc nh hng rt t n cc components khc .Nhim v ca
cc components ny l:

Model (mu) : Model m nhn nhim v cung cp d liu t c s d
liu v lu cc thng tin ni cha d liu. Tt c cac Business Logic
u c thc thi Model. D liu c nhp vo bi ngi s dng qua
View s c kim tra Model trc khi c lu vo c s d liu. Truy
xut d liu,s hp l ca d liu v data saving logic l cc thnh phn
ca Model.

View (hin th) : View trnh by vic hin th ca ng dng v nhn trch
nhim ly d liu t ngi s dng, gi cc yu cu n Controller ri sau
nhn tr li t Controller v hin th kt qu n ngi s dng. HTML,
JSPs, cc th vin Tag v cc file ngun l cc phn ca view component.

Controller (iu khin) : Controller l trung gian gia Model v View.
Controller c trch nhim nhn cc yu cu t Client. Khi m yu cu uc
nhn t Client,Controller s thc thi business logic thch hp t Model v
sau xut ra d liu cho user s dng View component. ActionServlet,
Action, ActionForm v struts-config.xml l cc thnh phn ca Controller.

Trang 13
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Cc mi quan h gia cc thnh phn

2. Mi quan h gia View v controller
Trong MVC truyn thng, cc view v controller c kt hp chc ch vi
nhau. Mi view c kt hp vi mt controller duy nht. Controller c
xem nh mt Strategy (s qun l) m view s dng cho u vo. View cng
chu trch nhim to ra cc khung nhn v controller mi.
C s logic rng cc khung nhn v cc controller c quan h mnh m vi
nhau, u vo v u ra ca mt ng ng c lin h chc ch vi nhau. Hu
ht cc nn GUI MVC, view v controller c trn trong mt i tng.
iu ny c gi l Document View. View v controller c kt hp thnh
view. Model tr nn c bit nh l ti liu.
Passive model lun phin chiu trch nhim nhiu hn v controller, v n
phi thng bo cho cc view khi n c s cp nht.
S hu ch web hin i ca MVC lun phin thm ch l nhiu hn cc MVC
truyn thng v vic chiu trch nhim ca view i vi controller. Controller
chiu trch nhim to ra v la chn cc view v view hng n vic chiu
trch nhim t hn i vi cc controller ca n.


3.Mi quan h gia Model v view
View ph thuc vo model. Cc s thay i i vi giao din model i hi
cc s thay i song song trong view.
Tht kh c c mt s tch bit r rnh gia model v view. Chng hn
nh, xt mt yu cu hin th mt cn cn m bng mu . u tin cn
cn, iu ny xut hin l yu cu u ra r rng v s kim tra c th c
t trong view theo mt hnh thc r rng nh sau:
if balance < 0 then red
iu ny c th xm phm n s tch bit ca cc thnh phn trong MVC.
Qua s phn tch trn yu cu thc s l hin th s cn bng c cng
iu bng mu v nh ngha ca cng iu = cn cn < 0= nn c c
trong model v l thuc v s m t min. Tht d dng cho tc nghip
chuyn ra ca model v chuyn vo view.


Trang 14
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Mi quan h gia model v controller
Controller ph thuc vo model. Cc s thay i i vi giao din model c
th yu cu s thay i song song i vi controller.


4. Cc li im ca MVC:
Giao din ngi s dng c kh nng thay th d dng
Cc view v cc controller khc nhau c th c thay i a ra s la
chn cc giao din ngi s dng i vi cng mt model. Chng hn nh,
cng mt d liu model c th c hin th bi biu bar, hay biu pie,
hoc spreadsheet.
Cc thnh phn hp thnh giao din ngi s dng
Bi v MVC i hi giao din ngi s dng ng dng c cu trc thnh
cc i tng k tha nhau v nh ngha cc quan h chun gia cc i
tng ny, cc phin bn chung ca cc i tng ny l c th c c.
Chng thng thng c gi l c thnh phn giao din kt hp vi cc view
v cc controller thnh mt i tng n. WACT l mt s n lc a ra
mt tp cc thnh phn phong ph tng t nhau i vi vic pht trin web
m duy tr c s tch bit gia view v controller. Cc thnh phn thc y
s s dng li v ct gim s cn thit i vi cc lp con c bit. Cc thnh
phn ny c bit nh l cc view c kh nng cm vo trong tuyn tnh
smlltalk MVC.
Nhiu view ng thi ca mt model
Nhiu view khc nhau c th hot ng ti cng mt thi im. Mi view m
t ng thi v c lp thng tin ging nhau t mt model. iu ny p dng
nhiu i vi GUI MVC hn l web MVC.
Cc khung nhn c ng b ha
C ch truyn s thay i m bo rng tt c cc khung nhn c th c
phn ng mt cch ng thi trng thi hin ti ca model.
D dng hn trong vic thay i giao din ngi s dng
Kim th d dng hn
Vi MVC tht d dng kim th chc nng chnh ca ng dng v n c
ng gi bi model.

5. Hn ch ca MVC
Gia tng s phc tp
S kt ni chc ch ca view v controller i vi model
S thay i i vi giao din model i hi s thay i song song trong view
v c th i hi s thay i thm i vi controller. S thay i code no
c th tr nn kh khn hn.
Tm n s cp nht d tha
C ch truyn s thay i c th khng hiu qu khi model thay i thng
xuyn i hi nhiu thng bo thay i. y khng phi l vn chung nu
passive model c s dng.
S kt ni chc ch gia view v controller
S tch bit r rng l rt kh, i khi l khng th





Trang 15
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Phn V
p dng kin trc MVC xy dng ng dng
trin khai thc t

Chng trnh : Java WebMail
Minh ha cch thc ng nhp h thng.

Tng quan ng dng:
Ngi dng tng tc vi cc component Controller (thng c th hin
bng cc Servlet) bng cch gi cc yu cu cho n. n lt mnh, cc
component Controller to nn cc thc th (instatiate) component Model
(thng c th hin bng cc JavaBean hoc bng cng ngh khc tng
ng), v thao tc n theo yu cu ca ng dng. Khi Model c khi to,
Controller s quyt nh chn View (thng th hin bi JSP) no trnh by
kt qu n ngi dng, View ny s tng tc vi Model trnh by kt qu.

1. Qui trnh thc hin :
1.1 .View :
thc hin phn View ca ng dng, chng ta dng 2 JSP n gin nh sau:

Trang login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head><title>Please Login</title></head>
<body>
<h1>Please enter your information for login seminar about Java (J2EE)</h1><br />
<form action="controller?action=login" method="post">
<table border="0">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body>
</html>



Trang 16
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Trang login.jsp ngi dng nhp vo username v password, thng gi l
trang JSP front-end. Thng tin ny c chuyn n Controller Servlet, bo
controller triu gi action l login



Trang Welcome.jsp


<jsp:useBean id="user" class="mvc.model.UserBean" scope="request" />
<html>
<head><title>Welcome</title></head>
<body>
<jsp:setProperty name="user" property="path"
value="<%=application.getRealPath("/members.mdb")%>" />
<h1>Welcome <jsp:getProperty name="user" property="name" /></h1>

</body>
</html>


Trang welcome.jsp hin th mt thng ip cho ngi dng vi tn c cung
cp t c s d liu do JavaBean truy xut. Tht ra trang View ch cn truy xut
JavaBean (jsp:getProperty) vi scope request (jsp:useBean). Bean ny c t trong
request bi Controller, nh chng ta s thy sau. Tuy nhin, y ta cng thit lp
thuc tnh path ca JavaBean minh ha vic dng i tng n application.
Thuc tnh path ch ra v tr thc ca c s d liu Access m ta truy xut bng
DSN-less.

1.2. Controller:
Mt Servlet thc hin phn controller trong ng dng chng ta:

Controller.class

package mvc.controller;
import mvc.controller.actions.LoginAction;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Trang 17
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import java.io.IOException;

public class Controller extends HttpServlet
{
protected void doGet( HttpServletRequest
httpServletRequest,HttpServletResponse httpServletResponse ) throws
ServletException, IOException
{
doPost( httpServletRequest, httpServletResponse );
}
protected void doPost( HttpServletRequest
httpServletRequest,HttpServletResponse httpServletResponse ) throws
ServletException, IOException
{
//Lay thuoc tinh action tu request
String theAction = httpServletRequest.getParameter(
"action" );
Action action = null;
if ( theAction.equalsIgnoreCase( "login" ) )
{
action = new LoginAction( httpServletRequest,
httpServletResponse );
}
// Thuc hien phuong thuc execute cua doi tuong lop
Action, tra ve mot duong dan page kieu string
String page = action.execute( httpServletRequest,
httpServletResponse );
RequestDispatcher rd =
httpServletRequest.getRequestDispatcher( page );
// forward trang ke tiep bang giao dien
RequestDispatcher
rd.forward( httpServletRequest, httpServletResponse );
}

}

Servlet trn ch dng mt tham s ca request l action quyt nh hnh
ng c triu gi. Trang login.jsp gi hnh ng login v i tng action lp
LoginAction s c triu gi. i tng action ny ci t mt giao din chun
(Action) vi mt phng thc execute, c cc i s l cc i tng Request v
Response. Phng thc ny tr v ng dn (page) n trang s gi k tip (phn
View), ngi dng chuyn tip (forward) n trang ny bng giao din
RequestDispatcher.






Trang 18
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Action.class

package mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public interface Action
{
public String execute( HttpServletRequest req, HttpServletResponse res );
}

LoginAction.class

package mvc.controller.actions;
import mvc.controller.Action;
import mvc.model.UserBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginAction implements Action
{
public LoginAction( HttpServletRequest request, HttpServletResponse response )
{

}

public String execute( HttpServletRequest req, HttpServletResponse res )
{
String username = req.getParameter( "username" );
String password = req.getParameter( "password" );
// Tao mot UserBean
try
{
UserBean user = new UserBean();
// Thiet lap cac thuoc tinh cua UserBean, co the thiet lap ca thuoc tinh path o day
user.setUser( username );
user.setPassword( password );
// Dat no vao trong request
req.setAttribute("user", user);
} catch ( Exception e )
{
System.out.println( e.getMessage() );
}

return "/welcome.jsp";
}
}

Trang 19
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Phng thc execute() ca lp LoginAction to (instantiate) mt i tng
Model mi (UserBean), t n vo trong Session, v tr v ng dn n trang k
tip tc welcome.jsp. Ch phn Controller ny s thit lp cc thuc tnh cho
JavaBean, nu y dng trang JSP th s c action jsp:setProperty

1.3. Model
Phn Model trong ng dng n gin ny ch c ng mt JavaBean

UserBean.class

package mvc.model;

import java.sql.ResultSet;
import mvc.util.*;

public class UserBean
{
private String user = "";
private String password = "";
private String name = "";
private String path = "";

public UserBean() throws ClassNotFoundException
{

}

public void setUser( String user )
{
this.user = user.toUpperCase();
}

public String getUser()
{
return user;
}

public void setPassword( String password )
{
this.password = password;
}

public String getPassword()
{
return password;
}

public void setPath( String path )
{

Trang 20
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
this.path = path;
}
public String getName()
{
try {
String strQuery = "SELECT name FROM accounts WHERE user = '"+ user +"'
AND password = '"+ password +"'";
ResultSet result = DataUtil.ReadData(strQuery, path);
while ( result.next() )
{
name = result.getString( 1 );
//if( user.equalsIgnoreCase(result.getString(1))
//&& password.equalsIgnoreCase(result.getString(2)));
}
} catch ( Exception e )
{
System.out.println( e.getMessage() );
}
return name;
}
}


DataUtil.class

package mvc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.*;

public class DataUtil
{
public static ResultSet ReadData(String SQL,String path) throws
Exception
{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Connection connect = DriverManager.getConnection
("jdbc:odbc:Driver={Microsoft Access Driver
(*.mdb)};"
+ "DBQ=" + path,
"", "" );
Statement stmt = connect.createStatement();
ResultSet result = stmt.executeQuery( SQL );
return result;
}
}


Trang 21
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Xy dng tp tin build.xml ng gi ng dng ra nh dng war dy trn
tomcat

Build.xml

<?xml version="1.0"?>
<project name="mvc_thien" default="all" basedir=".">
<property name="src.home" value="${basedir}/src" />
<property name="dist.home" value="${basedir}/dist" />
<property name="lib.home" value="${basedir}/web/WEB-INF/lib" />
<property name="web.home" value="${basedir}/web" />
<property name="database.home" value="${basedir}/database" />
<property name="build.home" value="${basedir}/build" />
<property name="build.classes.dir" value="${build.home}/classes" />
<property name="src.resources" value="${basedir}/src/resources" />
<property name="websrc.dir" value="${basedir}/pages" />
<property name="tomcat.home" value="C:\Program Files\Apache Software Foundation\Tomcat
5.0"/>

<!-- Build classpath -->
<path id="compile.classpath">
<fileset dir="${basedir}/web/WEB-INF/lib">
<include name="servlet-api.jar" />
</fileset>
<pathelement location="${build.classes.dir}" />
</path>

<target name="prepare">
<mkdir dir="${build.home}" />
<mkdir dir="${dist.home}" />

</target>

<target name="compile" depends="prepare" description="Compile Java sources">
<javac srcdir="${src.home}"
destdir="${build.home}"
debug="${compile.debug}"
deprecation="${compile.deprecation}"
optimize="${compile.optimize}">
<classpath refid="compile.classpath"/>
</javac>
<copy todir="${build.home}">
<fileset dir="${src.home}" excludes="**/*.java"/>
</copy>
</target>

<target name="dist" depends="compile" description="Create binary distribution">
<war destfile="${dist.home}/${ant.project.name}.war" webxml="${web.home}/WEB-
INF/web.xml">
<webinf dir="${web.home}/WEB-INF"/>
<lib dir="${lib.home}"/>
<classes dir="${build.home}"/>
<fileset dir="${web.home}" includes="*.*"/>
<fileset dir="${database.home}" includes="*.*"/>
</war>
</target>
<target name="deploy-tomcat">
<copy todir="${tomcat.home}/webapps">

Trang 22
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
<fileset dir="${dist.home}">
<include name="${ant.project.name}.war"/>
</fileset>
</copy>
</target>

<target name="all" depends="compile">
<war warfile="${build.home}/mvc.war" webxml="${src.resources}/web/web.xml">
<fileset dir="${basedir}/database" />
<fileset dir="${websrc.dir}" />
<classes dir="${build.classes.dir}" />
</war>
</target>

<target name="clean">
<delete dir="${build.home}"/>
</target>
</project>



2. Trin khai ng dng :

2.1. C s d liu
C s d liu Access: members.mdb c mt bng accounts






2.1. B tr cc tp tin trn Eclipse :














Trang 23
MVC Architecture & Struts Framework in J2EE (Java) 10/2007



2.3. Kt qu:














Trang 24
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Phn VI
Struts Framework

1. Struts 1.0:

1.1 Khi nim :
Struts l mt MVC Framework: Struts cung cp mt framework thng nht
deploy cc ng dng Servlet v JSP s dng kin trc MVC.
Struts l mt tp cc Utilities: Struts cung cp cc lp tin ch iu khin
hu ht cc tc v trong vic pht trin cc ng dng Web.
Struts l mt tp th vin cc th JSP ty chn (Custom JSP Tag): Struts cung
cp cc th vin th ty chn cho vic th hin cc thuc tnh ca bean, qun
l cc HTML forms, lp li cc kiu cu trc d liu, v a ra cc HTML c
iu kin.
Struts thc thi m hnh MVC
M hnh Struts Framework thc thi m hnh MVC bng cch s dng tp
hp cc th JSP, cc th ty chn JSP (custom JSP tag), v cc Java servlet.
Di y chng ta s m t ngn gn cch m Struts Framework nh x n
mi thnh phn trong m hnh MVC.


Hnh trn m t tin trnh m hu ht cc ng dng Struts phi tun theo.
Tin trnh ny c th c chia thnh 5 bc cn bn:
1. Request c to ra t mt View
2. Request c tip nhn bi mt ActionServlet (ng vai tr l mt
Controller), v ActionServlet ny s lookup URI cn thit trong file XML
v xc nh tn ca lp Action s thc hin cc bussiness logic cn thit.

Trang 25
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
3. Lp Action thc hin cc logic ca n trong cc thnh phn Model kt hp
vi ng dng.
4. Khi Action hon tt tin trnh s l ca n, n s tr iu khin v cho
ActionServlet. L mt phn ca thnh phn tr v, lp Action cung cp
mt kha xc nh kt qu qu ca tin trnh s l . ActionServlet s
dng kha ny xc nh kt qu s c forward n u trnh din
ra ngoi.
5. Yu cu c hon tt khi ActionServlet p ng n bng cch forward
yu cu n mt View c lin kt n tr v kha cp trn
bc 4, v View ny s trinh din kt qu ca Action.

Cu trc ca Struts 1.0



1.2. Cu trc ca Struts bao gm:
Mt hoc nhiu Action, mi action trong trang web s nh x chnh xc n
mt thnh phn <action> c nh ngha trong file struts-config.xml. Action
c triu gi bi ngi dng t mt trang HTML hoc JSP thng qua mt
lin kt hay thng qua thuc tnh action trong th <form>.
Mt thnh phn <action> s nh ngha mt lp ActionForm, trong mt s
trng hp, n s c s dng validate cc d liu trong form c
submit bi ngi s dng. N cng nh ngha lp Action no s c s
dng x l cc yu cu t pha ngi dng.

Trang 26
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
Mt lp ActionForm c th s dng mt hoc nhiu forward c nh ngha
trong th <action> ni cho mt ActionServlet tr v cc response tng
ng vi cc request ca ngi dng. Chng ta c th nh ngha nhiu forward
trong th <action-mapping>.

1.3. Cc thnh phn chnh ca mt ng dng Struts:
ActionServlet: ng vai tr nh l mt controller trong m hnh MVC, hay ni
cch khc ActionServlet l s thc thi controller ca Struts i vi m hnh
MVC. ActionServlet ly v cc request t pha ngi dng v nh x chng
n thnh phn <action> trong file struts-config.xml.
Action: nh ngha mt tc v c th c gi bi ngi dng. N cng nh
ngha lp s s l cc request t pha ngi dng v trang JSP s hin th kt
qu v cho ngi s dng.
Lp Action: cha ton b nhng s l cho cc yu cu ca ngi dng.
ActionForm: i km vi th <action> trong file struts-config.xml, n qun l
ton b cc d liu c submit ln t pha ngi dng v c th thc hin
validate cc d liu .
Trang JSP: c s dng tr v trang HTML th hin kt qu c
s l cho ngi dng.
1.4. Cc file cu hnh cn thit xy dng mt ng dng Struts:
web.xml: file ny cha ton b cc cu hnh ca ActionServlet, cc s nh x
ca cc yu cu t pha ngi dng n ActionServlet, v tt cc Struts Tag
Library Definitions (TLDs).
struts-config.xml: file ny cha tt c cc thng tin cu hnh cho mt ng
dng xy dng da trn Struts.

ApplicationResources.properties: file ny trung tm cha cc ni dung tnh
c s dng trong ton b ng dng Struts. N cho php cc nh pht trin
d dng thay i ni dung cc text v cc ni dung dng chung s dng trong
ng dng.


Cc th vin th Struts xy dng cc thnh phn trnh din trong mt ng
dng:
+ <templete>: cung cp cho nh pht trin ng dng mt tp cc th JSP
chia nh giao din ngi dng thnh cc thnh phn c th d dng tho rp.
+ <bean>: cung cp cho nh pht trin ng dng mt tp cc th JSP qun
l u ra t mt JavaBean.
+<logic>: c th c s dng ng dng cc iu kin logic trong mt
trang JSP.
+ <html>: c th s dng to ra cc thnh phn form





Trang 27
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
1.5. u im ca Struts (so vi MVC s dng RequestDispatcher)

- Cu hnh c tp trung da vo file:
Thay v vit hng lot nhng thng tin vo chng trnh Java, hu ht
nhng gi tr Struts c th hin trong file .xml v file property. Phng
php ny cho php ngi lp trnh Web v Java ch ch tm vo phn cng
vic c th ca h (ci t business logic, hin th nhng gi tr c th cho
clients, etc) m khng cn quan tm v tng th h thng.

- Form beans:
Trong JSP, ta c th s dng thuc tnh property=* vi jsp:setProperty
t ng sinh ra JavaBean component da trn nhng thng s yu cu
chuyn n. Apache Struts m rng thm kh nng ny v thm vo vi
tin ch khc, tt c nhm phc v cho vic n gin ha tin trnh x l
nhng thng s yu cu t client.

- Bean tags:
Apache Struts cung cp 1 tp custom JSP tags (c th l bean:write) cho
php d dng xut ra nhng thuc tnh ca JavaBean components.

- HTML tags:
Apache Struts cung cp 1 tp custom JSP tags to HTML forms - nhng
ci h tr cho JavaBean components. S h tr bean/form ny phc v 2
mc ch sau:
+ N cho php ta khi to cc gi tr field ca form t cc i tng Java.
+ N cho php ta hin th li cc form vi 1 vi hoc tt c nhng gi tr
nhp vo lc trc 1 cch nguyn vn.

- Kim tra gi tr cc field ca form :
Apache Struts tch hp sn nhng kh nng cho vic kim tra nhng gi tr
form c nh dng theo yu cu. Nu nhng gi tr khng nh dng
hoc nh dng sai, form c th t ng hin th nhng thng bo li. Cch
rng buc ny c th thc hin trn server (Java) hoc trn client
(JavaScript).

- Kim tra gi tr cc field ca form :
Struts h tr tnh nht qun ca MVC xuyn sut ng dng.

1.6. Nhc im ca Struts :

- Nhc im ca Struts :
s dng MVC vi chun RequestDispatcher, ta cn nghin cu su vi
chun JSP v Servlet APIs. s dng MVC vi Struts, ta cn phi hiu r
c framework rng ln v phc tp, n tng t nh vic tm hiu c ci
ct li ca h thng. iu bt li ny c bit ng k vi nhng d n
nh, nhng d n c t thi gian thc hin, v nhng lp trnh vin c t
kinh nghim; ta mt rt nhiu thi gian trong vic nghin cu Struts khi
thc hin n.



Trang 28
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
- t c ti liu h tr
So snh vi chun servlet v JSP APIs, Struts c t ti liu h tr hn nhiu.

- Less transparent:
Vi nhng ng dng Struts, c nhiu li bn di hn nhng ng dng
Web da trn ngn ng Java bnh thng. V th, ng dng Struts th:
+ Kh tm hiu.
+ Kh chun ha v nh gi.

- Cng nhc:
Struts kh p dng cc phng php khc


2. Struts 2.0:
Java framework pht trin cc ng dng web theo m hnh MVC.
Linh hot cho vic chun ha d liu ngi dng.
Cc file cu hnh s dng package v namespace qun l tt c cc
action.
D dng tch hp cc hp cc module ca nh cung cp th 3 (Hibernate,
Spring, Ajax).
S dng cc Interceptor.
Tch hp Inversion of Control.











Trang 29
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Phn VI
p dng Struts 2.0 Framework xy dng ng
dng trin khai thc t


Chng trnh: Qun L Nhn Vin
Minh ha chc nng cp nht ti khon.


I. Qui trnh thc hin :

1. Cc trang hin th (View)

Index.jsp

<%@page l anguage=" j ava" pageEncodi ng=" I SO- 8859- 1" %>
<! DOCTYPE HTML PUBLI C " - / / W3C/ / DTD HTML 4. 01
Tr ansi t i onal / / EN" >
<ht ml >
<head>
<t i t l e>I ndex page</ t i t l e>

<META HTTP- EQUI V=" Ref r esh"
CONTENT=" 0; URL=empl oyee/ get Empl oyeeLi st . act i on" >
</ head>

<body>
<h1>I ni t i al i zi ng. . . </ h1>
</ body>
</ ht ml >






Trang 30
MVC Architecture & Struts Framework in J2EE (Java) 10/2007


Employee.jsp

<%@page l anguage=" j ava" cont ent Type=" t ext / ht ml ;
char set =I SO- 8859- 1" pageEncodi ng=" I SO- 8859- 1" %>
<%@t agl i b pr ef i x=" s" ur i =" / st r ut s- t ags" %>
<! DOCTYPE ht ml PUBLI C " - / / W3C/ / DTD HTML 4. 01
Tr ansi t i onal / / EN" " ht t p: / / www. w3. or g/ TR/ ht ml 4/ l oose. dt d" >
<ht ml >
<head>
<met a ht t p- equi v=" Cont ent - Type" cont ent =" t ext / ht ml ;
char set =I SO- 8859- 1" >
<t i t l e>I nser t t i t l e her e</ t i t l e>
<SCRI PT t ype=" t ext / j avascr i pt " >
f unct i on edi t ( )
{
al er t ( " edi t . . . . . . . " ) ;
document . get El ement ByI d( " bt nAdd" ) . di sabl ed = t r ue;
document . get El ement ByI d( " bt nSave" ) . di sabl ed = f al se;
}
</ SCRI PT>
</ head>
<body>
<h3> Demo St r ut s 2. 0 Fr amewor k i n J 2EE </ h3>
<s: f i el der r or / >
<f or mi d=" f r mEmpl oyee" name=" Empl oyee" met hod=" post "
t heme=" si mpl e" >
<t abl e bor der =" 1" wi dt h=" 100%" >
<t r >
<t d>I D</ t d>
<t d st yl e=" wi dt h: 20%" >Name</ t d>
<t d st yl e=" wi dt h: 10%" >Sex</ t d>
<t d st yl e=" wi dt h: 15%" >Bi r t hday</ t d>
<t d st yl e=" wi dt h: 15%" >Ci t y</ t d>
<t d st yl e=" wi dt h: 30%" >Emai l </ t d>
<t d st yl e=" wi dt h: 10%" >Act i on</ t d>
</ t r >
<%- - l i st i s pr oper t y - - %>
<s: i t er at or val ue=" empl oyeeLi st " >
<t r >
<t d>
<s: pr oper t y val ue=" i d" / >
</ t d>
<t d>
<s: pr oper t y val ue=" name" / >
</ t d>
<t d>
<s: pr oper t y val ue=" se- x" / >
</ t d>
<t d al i gn=" cent er " >

Trang 31
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
<s: pr oper t y val ue=" bi r t hday" / >
</ t d>
<t d>
<s: pr oper t y val ue=" ci t y" / >
</ t d>
<t d>
<s: pr oper t y val ue=" emai l " / >
</ t d>
<t d al i gn=" cent er " >
<s: ur l i d=" ur l Del et e"
act i on=" Empl oyeeDel et e" >
<s: par amname=" i d"
val ue=" %{i d}" / >
</ s: ur l >

<s: a
hr ef =" %{ur l Del et e}" >Del et e</ s: a>

<s: ur l i d=" ur l Edi t "
act i on=" Empl oyeePr epar eUpdat e" >
<s: par amname=" i d" val ue=" %{i d}" / >
</ s: ur l >
<s: a hr ef =" %{ur l Edi t }"
oncl i ck=" r et ur n edi t ( ) ; " >Edi t </ s: a>
</ t d>
</ t r >
</ s: i t er at or >
</ t abl e>
</ f or m>
</ body>
</ ht ml >



Trang 32
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

Success.jsp

<%@page l anguage=" j ava" pageEncodi ng=" I SO- 8859- 1" %>
<%
St r i ng pat h = r equest . get Cont ext Pat h( ) ;
St r i ng basePat h =
r equest . get Scheme( ) +" : / / " +r equest . get Ser ver Name( ) +" : " +r eq
uest . get Ser ver Por t ( ) +pat h+" / " ;
%>

<! DOCTYPE HTML PUBLI C " - / / W3C/ / DTD HTML 4. 01
Tr ansi t i onal / / EN" >
<ht ml >
<head>
<base hr ef =" <%=basePat h%>" >

<t i t l e>My J SP ' Success. j sp' st ar t i ng page</ t i t l e>

<met a ht t p- equi v=" pr agma" cont ent =" no- cache" >
<met a ht t p- equi v=" cache- cont r ol " cont ent =" no- cache" >
<met a ht t p- equi v=" expi r es" cont ent =" 0" >
<met a ht t p- equi v=" keywor ds"
cont ent =" keywor d1, keywor d2, keywor d3" >
<met a ht t p- equi v=" descr i pt i on" cont ent =" Thi s i s my
page" >
<! - -
<l i nk r el =" st yl esheet " t ype=" t ext / css"
hr ef =" st yl es. css" >
- - >

</ head>

<body>
<h1>Successf ul ! . </ h1> <br >
</ body>
</ ht ml >



Trang 33
MVC Architecture & Struts Framework in J2EE (Java) 10/2007



Fail.jsp

<%@page l anguage=" j ava" pageEncodi ng=" I SO- 8859- 1" %>
<%
St r i ng pat h = r equest . get Cont ext Pat h( ) ;
St r i ng basePat h =
r equest . get Scheme( ) +" : / / " +r equest . get Ser ver Name( ) +" : " +r eq
uest . get Ser ver Por t ( ) +pat h+" / " ;
%>

<! DOCTYPE HTML PUBLI C " - / / W3C/ / DTD HTML 4. 01
Tr ansi t i onal / / EN" >
<ht ml >
<head>
<base hr ef =" <%=basePat h%>" >

<t i t l e>My J SP ' Fai l . j sp' st ar t i ng page</ t i t l e>

<met a ht t p- equi v=" pr agma" cont ent =" no- cache" >
<met a ht t p- equi v=" cache- cont r ol " cont ent =" no- cache" >
<met a ht t p- equi v=" expi r es" cont ent =" 0" >
<met a ht t p- equi v=" keywor ds"
cont ent =" keywor d1, keywor d2, keywor d3" >
<met a ht t p- equi v=" descr i pt i on" cont ent =" Thi s i s my
page" >
<! - -
<l i nk r el =" st yl esheet " t ype=" t ext / css"
hr ef =" st yl es. css" >
- - >

</ head>

<body>
<h1> I nval i d Empl oyee. </ h1> <br >
</ body>
</ ht ml >

Trang 34
MVC Architecture & Struts Framework in J2EE (Java) 10/2007





Update.jsp

<%@page l anguage=" j ava" cont ent Type=" t ext / ht ml ;
char set =I SO- 8859- 1"
pageEncodi ng=" I SO- 8859- 1" %>
<%@t agl i b pr ef i x=" s" ur i =" / st r ut s- t ags" %>
<! DOCTYPE ht ml PUBLI C " - / / W3C/ / DTD HTML 4. 01
Tr ansi t i onal / / EN" " ht t p: / / www. w3. or g/ TR/ ht ml 4/ l oose. dt d" >
<ht ml >
<head>
<met a ht t p- equi v=" Cont ent - Type" cont ent =" t ext / ht ml ;
char set =I SO- 8859- 1" >
<t i t l e>I nser t t i t l e her e</ t i t l e>
</ head>
<body>
<f or mname=" f r mEmpl oyee" met hod=" post " >
<t abl e>
<t r >
<t d> <s: t ext f i el d l abel =" Name" name=" name"
val ue=" %{name}" / ></ t d>
</ t r >
<t r >
<t d> <s: r adi o l abel =" Sex"
val ue=" %{sex}" name=" sex"
l i st =" {' Mal e' , ' Femal e' }" ></ s: r adi o> </ t d>
</ t r >
<t r >
<t d> <s: t ext f i el d l abel =" Bi r t hDay"
val ue=" %{bi r t hday}" name=" bi r t hday" / ></ t d>
</ t r >
<t r >
<t d> <s: sel ect l abel =" Ci t y" name=" ci t y"
val ue=" %{ci t y}" l i st =" {' Ho Chi Mi nh' , ' Ha Noi ' , ' Da
Nang' }" ></ s: sel ect > </ t d>

Trang 35
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
</ t r >
<t r >
<t d> <s: t ext f i el d l abel =" Emai l "
name=" emai l " val ue=" %{emai l }" / ></ t d>
</ t r >
<t r >
<t d> <s: t ext ar ea l abel =" Hi st or y"
name=" hi st or y" val ue=" %{hi st or y}" col s=" 20" r ows=" 3"
/ ></ t d>
</ t r >
<t r >
<t d>
<s: submi t i d=" bt nAdd" name=" bt nAdd"
val ue=" Add" act i on=" Empl oyeeAdd" t heme=" si mpl e"
al i gn=" r i ght " / >
<s: submi t i d=" bt nSave" name=" bt nSave"
val ue=" Save" act i on=" Empl oyeeUpdat e" t heme=" si mpl e"
al i gn=" r i ght " >
</ s: submi t >
<s: submi t i d=" bt nGet Li st "
name=" bt nGet Li st " val ue=" Get Empl oyee Li st "
act i on=" get Empl oyeeLi st " / >

</ t d>
</ t r >
</ t abl e>

</ f or m>
</ body>
</ ht ml >



Trang 36
MVC Architecture & Struts Framework in J2EE (Java) 10/2007




2. Action :

EmployeeAction.class

package net.vietcore.demo.action;
import net.vietcore.demo.bean.Employee;
import net.vietcore.demo.bean.EmployeeService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;
public class EmployeeAction extends ActionSupport implements ModelDriven,
Preparable{

/**
*
*/
private static final long serialVersionUID = 1L;

private int id;
private Employee employee;
private EmployeeService service = new EmployeeService();

Trang 37
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
/*
* This method is call automatically when the Class is called.
*
*/
public void prepare() throws Exception {
System.out.println("prepare() in Employee Action");
System.out.println("EmployeeID = "+id);
if (id==0){
employee = new Employee();
System.out.println("Tao moi ");
}else {
employee = service.findById(id);
System.out.println("Tim ");
}

}
/*
* This method is call automatically when the Class is called.
*
*/
public Object getModel() {
System.out.println("getModel() in Employee Action");
return employee;
}

public String addEmployee(){
System.out.println("addEmployee() in Employee Action");
service.addEmployee(employee);
return SUCCESS;

}
public String deleteEmployee(){
System.out.println("deleteEmployee() in Employee Action");
System.out.println(employee.getId());
service.deleteEmployee(employee.getId());
return SUCCESS;

}
public String updateEmployee(){
System.out.println("updateEmployee() in Employee Action");
service.updateEmployee(employee);
return SUCCESS;

Trang 38
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
}

public String execute() throws Exception{
System.out.println("execute() in Employee Action");
return SUCCESS;
}
public String input() throws Exception{
System.out.println("input() in Employee Action");
return INPUT;
}
}


ListEmployeeAction.class

package net.vietcore.demo.action;

import java.util.List;

import net.vietcore.demo.bean.EmployeeService;

import com.opensymphony.xwork2.ActionSupport;

public class ListEmployeeAction extends ActionSupport{

/**
*
*/
private static final long serialVersionUID = 1L;
EmployeeService service = new EmployeeService();
private List employeeList;

public List getEmployeeList() {
System.out.println("getEmployeeList() in class
ListEmployeeAction");
return employeeList;
}

public String execute() throws Exception{
System.out.println("execute() in class ListEmployeeAction");
service.addEmployeeToList();
employeeList = service.list();
return SUCCESS;
}
}






Trang 39
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
3. Bean:

Employee.class

package net . vi et cor e. demo. bean;

public class Empl oyee {

private int i d;

private St r i ng name;

private St r i ng sex;

private St r i ng bi r t hday;

private St r i ng ci t y;

private St r i ng emai l ;

private St r i ng hi st or y;

public St r i ng get Bi r t hday( ) {
return bi r t hday;
}

public void set Bi r t hday( St r i ng bi r t hday) {
this. bi r t hday = bi r t hday;
}

public St r i ng get Ci t y( ) {
return ci t y;
}

public void set Ci t y( St r i ng ci t y) {
this. ci t y = ci t y;
}

public St r i ng get Emai l ( ) {
return emai l ;
}

public void set Emai l ( St r i ng emai l ) {
this. emai l = emai l ;
}

public St r i ng get Hi st or y( ) {
return hi st or y;
}


Trang 40
public void set Hi st or y( St r i ng hi st or y) {
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
this. hi st or y = hi st or y;
}

public int get I d( ) {
return i d;
}

public void set I d( int i d) {
this. i d = i d;
}

public St r i ng get Name( ) {
return name;
}

public void set Name( St r i ng name) {
this. name = name;
}

public St r i ng get Sex( ) {
return sex;
}

public void set Sex( St r i ng sex) {
this. sex = sex;
}
}


EmployeeService.class

package net.vietcore.demo.bean;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import net.vietcore.demo.utils.DataUtils;
public class EmployeeService {
private ArrayList<Employee> employeeList;

public ArrayList<Employee> list(){
return employeeList;
}
public void addEmployeeToList(){
//System.out.println("addEmployeeToList() in Employee
Action....");

ResultSet rs;

Trang 41
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
int i=0;
//PreparedStatement pstmt = null;
try {
//DataUtils.connectDb();
//pstmt =
DataUtils.getConnect().prepareStatement("Select * from tblEmployee");
rs= DataUtils.Doc("Select * from tblEmployee");
//rs = pstmt.executeQuery();
employeeList = new ArrayList<Employee>();
while (rs.next()) {
i++;

Employee employee = new Employee();

employee.setId(rs.getInt("ID"));
employee.setName(rs.getString("name"));
employee.setSex(rs.getString("sex"));
employee.setBirthday(rs.getString("birthday"));
employee.setCity(rs.getString("city"));
employee.setEmail(rs.getString("email"));
employee.setHistory(rs.getString("history"));
employeeList.add(employee);
}
} catch (Exception e) {
//e.printStackTrace();
}
System.out.println(i);
}
public int addEmployee(Employee employee){
System.out.println("addEmployee method in EmployeeService
class");
int ret = -1;
PreparedStatement pstmt = null;
try {
DataUtils.connectDb();
pstmt =
DataUtils.getConnect().prepareStatement("INSERT INTO tblEmployee (Name,
Sex, Birthday, City, Email, History) VALUES(?, ?, ?, ?, ?, ?)");
pstmt.setString(1, employee.getName());
pstmt.setString(2, employee.getSex());
pstmt.setString(3, employee.getBirthday());
pstmt.setString(4, employee.getCity());
pstmt.setString(5, employee.getEmail());
pstmt.setString(6, employee.getHistory());

int result = pstmt.executeUpdate();

if(result > 0)
{

Trang 42
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
System.out.println("Employee insert
successfully");
ret = 1;
}
else
{
ret = 0;
}

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

} finally
{
if(pstmt != null)
{
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
DataUtils.disconnectDb();
}

return ret;
}

public int updateEmployee(Employee employee){
System.out.println("updateEmployee method in
EmployeeService class");
int ret = -1;
PreparedStatement pstmt = null;
try {
DataUtils.connectDb();
pstmt =
DataUtils.getConnect().prepareStatement("UPDATE tblEmployee SET Name=?,
Sex=?, Birthday=?, City=?, Email=?, History=? WHERE ID=?");
pstmt.setString(1, employee.getName());
pstmt.setString(2, employee.getSex());
pstmt.setString(3, employee.getBirthday());
pstmt.setString(4, employee.getCity());
pstmt.setString(5, employee.getEmail());
pstmt.setString(6, employee.getHistory());
pstmt.setInt(7, employee.getId());

int result = pstmt.executeUpdate();

if(result > 0)
{

Trang 43
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
System.out.println("Employee saved
successfully");
ret = 1;
}
else
{
ret = 0;
}

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

} finally
{
if(pstmt != null)
{
try {
pstmt.close();
} catch (SQLException e) {

e.printStackTrace();
}
}
DataUtils.disconnectDb();
}
return ret;

}

public int deleteEmployee(int id){
System.out.println("deleteEmployee method in
EmployeeService class");
int ret = -1;
PreparedStatement pstmt = null;
try {
DataUtils.connectDb();
pstmt =
DataUtils.getConnect().prepareStatement("DELETE FROM tblEmployee
WHERE id=?");
pstmt.setInt(1, id);

pstmt.executeUpdate();

ret = 1;

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

} finally
{

Trang 44
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
if(pstmt != null)
{
try {
pstmt.close();
} catch (SQLException e) {

e.printStackTrace();
}
}
DataUtils.disconnectDb();
}
return ret;
}

public Employee findById(int id){
addEmployeeToList();
System.out.println("findById method in EmployeeService
class");
for (Employee employee : employeeList) {
if(employee.getId()==id)
return employee;
}
return null;
}

public Employee getEmployee(int id){
Employee employee = new Employee();
ResultSet rs = null;
PreparedStatement pstmt = null;
try {
DataUtils.connectDb();
pstmt =
DataUtils.getConnect().prepareStatement("SELECT * FROM tblEmployee
WHERE id=?");
pstmt.setInt(1, id);

rs = pstmt.executeQuery();
while (rs.next()) {


employee.setId(rs.getInt("ID"));
employee.setName(rs.getString("Name"));
employee.setSex(rs.getString("Sex"));
employee.setBirthday(rs.getString("Birthday"));
employee.setCity(rs.getString("City"));
employee.setEmail(rs.getString("Email"));
employee.setHistory(rs.getString("History"));

}


Trang 45
MVC Architecture & Struts Framework in J2EE (Java) 10/2007

} catch (Exception e) {
e.printStackTrace();
} finally
{
if(pstmt != null)
{
try {
pstmt.close();
} catch (SQLException e) {

e.printStackTrace();
}
}
if(rs != null)
{
//rs.close();
}
DataUtils.disconnectDb();
}

return employee;
}
}


4. Utils :

DataUtils.class

package net.vietcore.demo.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DataUtils {

private static Connection con;

private static int count;

public static void connectDb() {
try {
// Connect Normal
String DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String connString = "jdbc:odbc:dataStruts2";
Class.forName(DBDriver).newInstance();
con = DriverManager.getConnection(connString);

Trang 46
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
// chuong trinh DEMO
System.out.println("Connection number: " +
(++count));

} catch (ClassNotFoundException cnfe) {
try {
throw new Exception("Cannot find the specified
driver.", cnfe);
} catch (Exception e) {
}
} catch (Exception e) {
System.out.println("Error, class Connect \n Method:
connectDb()");
System.out.println(e);
}
}

public static Connection getConnect() {
return con;
}

public static void disconnectDb() {
try {
System.out.println("Disconnecting..." + count);
con.close();
} catch (SQLException sqle) {

System.out.println(sqle.getMessage());
}
}

public static ResultSet Doc(String chuoi_lenh) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=
DriverManager.getConnection("jdbc:odbc:dataStruts2");
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery(chuoi_lenh);

return rs;
}

}


5. Struts.xml

<! DOCTYPE st r ut s PUBLI C
" - / / Apache Sof t war e Foundat i on/ / DTD St r ut s
Conf i gur at i on 2. 0/ / EN"

Trang 47
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
" ht t p: / / st r ut s. apache. or g/ dt ds/ st r ut s- 2. 0. dt d" >

<st r ut s>
<package name=" t okenPackage" namespace=" / empl oyee"
ext ends=" st r ut s- def aul t " >


<act i on name=" get Empl oyeeLi st "
cl ass=" net . vi et cor e. demo. act i on. Li st Empl oyeeAct i on"
met hod=" execut e" >

<r esul t name=" success" >/ Empl oyee. j sp</ r esul t >

<! - - <r esul t name=" er r or " >/ er r or . j sp</ r esul t >
- - >
</ act i on>

<act i on name=" Empl oyeeI nput " met hod=" i nput "
cl ass=" net . vi et cor e. demo. act i on. Empl oyeeAct i on" >
<r esul t
name=" i nput " >/ Empl oyee. j sp</ r esul t >
</ act i on>
<act i on name=" Empl oyeeAdd" met hod=" addEmpl oyee"
cl ass=" net . vi et cor e. demo. act i on. Empl oyeeAct i on" >
<r esul t t ype=" r edi r ect -
act i on" >get Empl oyeeLi st </ r esul t >
<r esul t name=" er r or " >er r or . j ps</ r esul t >
</ act i on>
<act i on name=" Empl oyeeDel et e"
met hod=" del et eEmpl oyee"
cl ass=" net . vi et cor e. demo. act i on. Empl oyeeAct i on" >
<r esul t
t ype=" r edi r ect " >get Empl oyeeLi st . act i on</ r esul t >
</ act i on>

<act i on name=" Empl oyeePr epar eUpdat e"
cl ass=" net . vi et cor e. demo. act i on. Empl oyeeAct i on" >
<r esul t >/ Updat e. j sp</ r esul t >
<i nt er cept or - r ef
name=" par amsPr epar ePar amsSt ack" / >
</ act i on>
<act i on name=" Empl oyeeUpdat e"
met hod=" updat eEmpl oyee"
cl ass=" net . vi et cor e. demo. act i on. Empl oyeeAct i on" >
<r esul t t ype=" r edi r ect -
act i on" >get Empl oyeeLi st </ r esul t >
</ act i on>

</ package>
</ st r ut s>


Trang 48
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
6. Build.xml:

<pr oj ect name=" St r ut s2" def aul t =" di st " basedi r =" . " >

<pr oper t y name=" app. ver si on" val ue=" 0. 1- dev" / >
<pr oper t y name=" bui l d. home" val ue=" ${basedi r }/ bui l d" / >
<pr oper t y name=" di st . home" val ue=" ${basedi r }/ di st " / >
<pr oper t y name=" sr c. home" val ue=" ${basedi r }/ sr c" / >
<pr oper t y name=" web. home" val ue=" ${basedi r }/ web" / >
<pr oper t y name=" l i b. home" val ue=" ${basedi r }/ web/ WEB-
I NF/ l i b" / >


<pr oper t y name=" compi l e. debug" val ue=" t r ue" / >
<pr oper t y name=" compi l e. depr ecat i on" val ue=" f al se" / >
<pr oper t y name=" compi l e. opt i mi ze" val ue=" t r ue" / >

<pr oper t y name=" t omcat . home" val ue=" C: \ Pr ogr am
Fi l es\ Apache Sof t war e Foundat i on\ Tomcat 5. 5" / >

<pat h i d=" compi l e. cl asspat h" >
<f i l eset di r =" ${l i b. home}" i ncl udes=" **/ *. j ar " / >
</ pat h>

<t ar get name=" pr epar e" descr i pt i on=" Pr epar e some
necessar y st eps" >
<mkdi r di r =" ${bui l d. home}" / >
<mkdi r di r =" ${di st . home}" / >
</ t ar get >

<t ar get name=" cl ean" descr i pt i on=" Del et e ol d bui l d and
di st di r ect or i es" >
<del et e di r =" ${bui l d. home}" / >
<del et e di r =" ${di st . home}" / >
</ t ar get >

<t ar get name=" compi l e" depends=" pr epar e"
descr i pt i on=" Compi l e J ava sour ces" >
<j avac sr cdi r =" ${sr c. home}"
dest di r =" ${bui l d. home}"
debug=" ${compi l e. debug}"
depr ecat i on=" ${compi l e. depr ecat i on}"
opt i mi ze=" ${compi l e. opt i mi ze}" >
<cl asspat h r ef i d=" compi l e. cl asspat h" / >
</ j avac>
<! - - <copy t odi r =" ${bui l d. home}" >
<f i l eset di r =" ${sr c. home}" excl udes=" **/ *. j ava" / >
</ copy>- - >
</ t ar get >


Trang 49
MVC Architecture & Struts Framework in J2EE (Java) 10/2007
<t ar get name=" di st " depends=" compi l e" descr i pt i on=" Cr eat e
bi nar y di st r i but i on" >
<war dest f i l e=" ${di st . home}/ ${ant . pr oj ect . name}. war "
webxml =" ${web. home}/ WEB- I NF/ web. xml " >
<webi nf di r =" ${web. home}/ WEB- I NF" / >
<! - - <l i b di r =" ${l i b. home}" / >- - >
<! - - <cl asses di r =" ${bui l d. home}" / >- - >
<f i l eset di r =" ${web. home}" i ncl udes=" *. *" / >
<! - - <zi pf i l eset di r =" ${web. home}/ css" pr ef i x=" css" / > - -
>
<! - - <zi pf i l eset di r =" ${web. home}/ i mages"
pr ef i x=" i mages" / > - - >
<! - - <f i l eset di r =" ${web. home}" i ncl udes=" *. j sp" / >- - >
</ war >
</ t ar get >
<t ar get name=" depl oy- t omcat " >
<copy t odi r =" ${t omcat . home}/ webapps" >
<f i l eset di r =" ${di st . home}" >
<i ncl ude name=" ${ant . pr oj ect . name}. war " / >
</ f i l eset >
</ copy>
</ t ar get >
</ pr oj ect >



II . Trin Khai ng Dng:

1. C s d liu:



2 . B tr cc tp tin trn Eclipse :


Trang 50
MVC Architecture & Struts Framework in J2EE (Java) 10/2007























Trang 51

You might also like