Professional Documents
Culture Documents
10/2007
TRNG I HC KHOA HC T NHIN KHOA CNG NGH THNG TIN B MN CNG NGH PHN MM
N MN
Thng 10/2007
Trang 1
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
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
Trang 3
10/2007
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
10/2007
Trang 5
10/2007
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).
Trang 6
10/2007
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
10/2007
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
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
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.
Cc bc x l ca 1 request
Trang 10
MVC Architecture & Struts Framework in J2EE (Java) 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
10/2007
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
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
10/2007
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
10/2007
Trang 14
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
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.
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> </td> </tr> </table> </form> </body> </html>
Trang 16
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) import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import java.io.IOException;
10/2007
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
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
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
10/2007
} 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
10/2007
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}/WEBINF/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
10/2007
Trang 23
10/2007
2.3. Kt qu:
Trang 24
10/2007
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
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.
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>.
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
10/2007
Trang 28
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
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.
Trang 30
10/2007
Employee.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <SCRIPT type="text/javascript"> function edit() { alert("edit......."); document.getElementById("btnAdd").disabled = true; document.getElementById("btnSave").disabled = false; } </SCRIPT> </head> <body> <h3> Demo Struts 2.0 Framework in J2EE </h3> <s:fielderror/> <form id="frmEmployee" name="Employee" method="post" theme="simple"> <table border="1" width="100%"> <tr> <td>ID</td> <td style="width: 20%">Name</td> <td style="width: 10%">Sex</td> <td style="width: 15%">Birthday</td> <td style="width: 15%">City</td> <td style="width: 30%">Email</td> <td style="width: 10%">Action</td> </tr> <%-- list is property --%> <s:iterator value="employeeList"> <tr> <td> <s:property value="id" /> </td> <td> <s:property value="name" /> </td> <td> <s:property value="se-x"/> </td> <td align="center"> Trang 31
10/2007
<s:property value="birthday" /> </td> <td> <s:property value="city" /> </td> <td> <s:property value="email" /> </td> <td align="center"> <s:url id="urlDelete" action="EmployeeDelete"> <s:param name="id" value="%{id}"/> </s:url> <s:a href="%{urlDelete}">Delete</s:a> <s:url id="urlEdit" action="EmployeePrepareUpdate"> <s:param name="id" value="%{id}"/> </s:url> <s:a href="%{urlEdit}" onclick="return edit();">Edit</s:a> </td> </tr> </s:iterator> </table> </form> </body> </html>
Trang 32
10/2007
Success.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+req uest.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Success.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-<link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>Successful!.</h1> <br> </body> </html>
Trang 33
10/2007
Fail.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+req uest.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Fail.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-<link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1> Invalid Employee.</h1> <br> </body> </html> Trang 34
10/2007
Update.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form name="frmEmployee" method="post"> <table> <tr> <td> <s:textfield label="Name" name="name" value="%{name}"/></td> </tr> <tr> <td> <s:radio label="Sex" value="%{sex}"name="sex" list="{'Male','Female'}"></s:radio> </td> </tr> <tr> <td> <s:textfield label="BirthDay" value="%{birthday}" name="birthday"/></td> </tr> <tr> <td> <s:select label="City" name="city" value="%{city}" list="{'Ho Chi Minh','Ha Noi','Da Nang'}"></s:select> </td> Trang 35
10/2007
<td> <s:textfield label="Email" name="email" value="%{email}"/></td> </tr> <tr> <td> <s:textarea label="History" name="history" value="%{history}" cols="20" rows="3" /></td> </tr> <tr> <td> <s:submit id="btnAdd" name="btnAdd" value="Add" action="EmployeeAdd" theme="simple" align="right"/> <s:submit id="btnSave" name="btnSave" value="Save" action="EmployeeUpdate" theme="simple" align="right"> </s:submit> <s:submit id="btnGetList" name="btnGetList" value="Get Employee List" action="getEmployeeList"/> </td> </tr> </table> </form> </body> </html>
Trang 36
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
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) } 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; } }
10/2007
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
10/2007
3. Bean:
Employee.class
package net.vietcore.demo.bean; public class Employee { private int id; private String name; private String sex; private String birthday; private String city; private String email; private String history; public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHistory() { return history; } public void setHistory(String history) { Trang 40
MVC Architecture & Struts Framework in J2EE (Java) this.history = history; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
10/2007
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
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) 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; }
10/2007
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) 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
10/2007
MVC Architecture & Struts Framework in J2EE (Java) if(pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } DataUtils.disconnectDb(); } return ret; }
10/2007
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
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) // chuong trinh DEMO System.out.println("Connection number: " + (++count));
10/2007
} 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 struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" Trang 47
10/2007
<action name="getEmployeeList" class="net.vietcore.demo.action.ListEmployeeAction" method="execute"> <result name="success">/Employee.jsp</result> <!-- <result name="error">/error.jsp</result> --> </action> <action name="EmployeeInput" method="input" class="net.vietcore.demo.action.EmployeeAction"> <result name="input">/Employee.jsp</result> </action> <action name="EmployeeAdd" method="addEmployee" class="net.vietcore.demo.action.EmployeeAction"> <result type="redirectaction">getEmployeeList</result> <result name="error">error.jps</result> </action> <action name="EmployeeDelete" method="deleteEmployee" class="net.vietcore.demo.action.EmployeeAction"> <result type="redirect">getEmployeeList.action</result> </action> <action name="EmployeePrepareUpdate" class="net.vietcore.demo.action.EmployeeAction"> <result>/Update.jsp</result> <interceptor-ref name="paramsPrepareParamsStack"/> </action> <action name="EmployeeUpdate" method="updateEmployee" class="net.vietcore.demo.action.EmployeeAction"> <result type="redirectaction">getEmployeeList</result> </action> </package> </struts>
Trang 48
10/2007
6. Build.xml:
<project name="Struts2" default="dist" basedir="."> <property name="app.version" <property name="build.home" <property name="dist.home" <property name="src.home" <property name="web.home" <property name="lib.home" INF/lib"/> value="0.1-dev"/> value="${basedir}/build"/> value="${basedir}/dist"/> value="${basedir}/src"/> value="${basedir}/web"/> value="${basedir}/web/WEB-
<property name="compile.debug" value="true"/> <property name="compile.deprecation" value="false"/> <property name="compile.optimize" value="true"/> <property name="tomcat.home" value="C:\Program Files\Apache Software Foundation\Tomcat 5.5"/> <path id="compile.classpath"> <fileset dir="${lib.home}" includes="**/*.jar"/> </path> <target name="prepare" description="Prepare some necessary steps"> <mkdir dir="${build.home}"/> <mkdir dir="${dist.home}"/> </target> <target name="clean" description="Delete old build and dist directories"> <delete dir="${build.home}"/> <delete 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>
Trang 49
10/2007
<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="*.*"/> <!-- <zipfileset dir="${web.home}/css" prefix="css"/> -> <!--<zipfileset dir="${web.home}/images" prefix="images"/> --> <!--<fileset dir="${web.home}" includes="*.jsp"/>--> </war> </target> <target name="deploy-tomcat"> <copy todir="${tomcat.home}/webapps"> <fileset dir="${dist.home}"> <include name="${ant.project.name}.war"/> </fileset> </copy> </target> </project>
Trang 50
10/2007
Trang 51