You are on page 1of 20

9/10/2011

Ni dung

B mn Cng ngh Phn mm


Vin CNTT & TT
Trng i hc Bch Khoa H Ni

1. Struts l g, ti sao s dng Struts?


2. Kin trc ca Struts

LP TRNH WEB HNG JAVA


Bi 19: C bn v Struts

Ging vin: ThS. Trnh Tun t


B mn CNPM
Email: trinhtuandat.bk@gmail.com/dattt@soict.hut.edu.vn
DatTT-DSE-SOICT-HUST
1

Controller
Model
View

3. web.xml
4. Internationalization
5. Input Validation
6. X l li
7. Chn View tr v
DatTT-DSE-SOICT-HUST

Jakarta Struts

1.1. Struts l g?

Struts l mt Web application framework m


ngun m, l mt phn ca Apache Jakarta
project

DatTT-DSE-SOICT-HUST

DatTT-DSE-SOICT-HUST

1.1. Struts l g?

ng dng Struts l ng dng Web, chy c trn bt k


Sevlet container no, bao gm c tt c cc J2EE
compliant App servers

Tun theo cc mu thit k

Singleton, composition view, delegate


D hc & s dng

C km cc th vin th JSP custom tag


DatTT-DSE-SOICT-HUST

Struts cho php cc LTV ...

Model-View-Controller (MVC) framework


c s dng xy dng cc ng dng Web s
dng Servlets v JSPs

http://jakarta.apache.org/struts/

Pht trin ng dng web JSP/Servlet theo


m hnh MVC
S dng cc i tng c sn ca framework
trong file cu hnh XML
S dng cc mu thit k xy dng sn ca
framework
S dng cc c tnh nng cao nh input
validation, internationalization
DatTT-DSE-SOICT-HUST

9/10/2011

1.2. Ti sao s dng Struts?

1.2. Ti sao s dng Struts

DatTT-DSE-SOICT-HUST

Struts m nhim nhng phn phc tp nht khi


xy dng ng dng MVC
D hc v s dng
Nhiu tnh nng
Nhiu cng c h tr ca bn th 3 (third party
tools)
Linh ng v d m rng (Flexible & extensible)
Cng ng s dng ng o
n nh v vn ang lin tc pht trin
M ngun m
DatTT-DSE-SOICT-HUST

1.2. Ti sao s dng Struts?

Tch hp tt vi Java EE (J2EE)


H tr taglib tt
X l li thng nht, theo c 2 c ch
programmatic v declarative
Tch hp vi Tiles framework (Struts nng
cao)

DatTT-DSE-SOICT-HUST

2. Kin trc ca Struts

Model-View-Control (model 2)

DatTT-DSE-SOICT-HUST

10

Struts hot ng nh th no

MVC Design Pattern


1
Request

BROWSER

(Controller)
Servlet

Redirect

5
Response

(View)
JSP

(Model)
Java Bean

Servlet Container
DatTT-DSE-SOICT-HUST

(EIS)
11

DatTT-DSE-SOICT-HUST

12

9/10/2011

Struts: Kin trc MVC

Struts: Kin trc MVC

Controller trung tm iu hnh lung ng dng, y


quyn cho cc b x l thch hp gi l Action
Action Handlers c th s dng cc model
components
Model ng gi trng thi hoc logic nghip v
iu khin c chuyn tip (forward) cho
Controller vi View ph hp

Vic forward c th c xc nh bng vic tra cu t


tp cc mappings trong file cu hnh, cho php tng
linh ng ga tng View v Model
DatTT-DSE-SOICT-HUST

3 thnh phn chnh trong Struts

Struts tp trung ch yu vo phn Controller

13

Servlet controller (Controller)


Java Server Pages hoc bt k cng ngh hin
th no khc (View)
Application Business Logic dng bt k ph hp
vi ng dng (Model)
Struts c s c lp gia Model & View
Struts c th s dng bt k cng ngh Model &
View no
DatTT-DSE-SOICT-HUST

14

Struts: Kin trc MVC

File cu hnh cha cc action mappings

nh x URL vi cc Action
Controller s dng cc mapping ny tr v
HTTP requests cho Action no ca ng dng
Xc nh forwarding/navigation

2.1. Controller

Mapping phi m t c

ng dn ca yu cu: request path


Action x l request nhn c

DatTT-DSE-SOICT-HUST

15

Controller c nhim v g?

DatTT-DSE-SOICT-HUST

16

Cc thnh phn Controller

Ging nh 1 switch trong kin trc MVC


Tt c cc request phi i qua controller
Chu trch nhim iu khin lung cho cc
x l request (action mapping)

c file cu hnh xc nh lung iu khin

DatTT-DSE-SOICT-HUST

17

DatTT-DSE-SOICT-HUST

18

9/10/2011

Nhim v ca LTV

Controller trong Struts Framework

Struts framework cung cp servlet:

org.apache.struts.action.ActionServlet
Phi cu hnh Servlet mapping cho servlet ny
trong file web.xml

Cc cu hnh lin quan ti Struts khc c


to lp trong file struts-config.xml

Vit lp Action (k tha lp Action) cho mi


request c th nhn c

Vit action mapping trong file cu hnh

Action Mapping nh ngha cc nh x gia URI


ca request gi n vi 1 lp Action c th

struts-config.xml

Cp nht file web.xml, thc hin mapping


cho ActionServlet

DatTT-DSE-SOICT-HUST

Phi override phng thc execute() (phng


thc perform() trong Struts 1.0)

web.xml

19

DatTT-DSE-SOICT-HUST

20

Cc thnh phn Controller trong Struts


Framework

ActionServlet (Struts cung cp)


RequestProcessor (Struts 1.1) (Struts cung cp)

Action (LTV vit)

Action Mapping (To bi LTV)

2.1.1. ActionServlet
(Framework cung cp)

Cho mi module
LTV k tha lp Action do Struts cung cp
LTV to cc action mapping trong file struts-config.xml
Struts framework s to cc i tng ActionMapping v
truyn chng cho i tng Action

DatTT-DSE-SOICT-HUST

21

DatTT-DSE-SOICT-HUST

Nhim v ca ActionServlet?

Nhim v ca ActionServlet? (2)

Thc hin vai tr ca Controller

X l cc user requests
Xc nh xem user cn g, cn c o request
nhn c
Ly d liu t model (nu cn thit), v
Ly ra view ph hp tr v cho ngi dng

Chu trch nhim khi to v dn dp ti


nguyn

y nhim hu ht nhng cng vic ny cho


lp Action
DatTT-DSE-SOICT-HUST

22

loads cc cu hnh ng dng trong web.xml


Duyt ln lt cc goes through an enumeration
of all init-param elements, looking for those
elements who's name starts with config/ for
modules
truy cp vo module foo, s dng URL nh:

23

http://localhost:8080/myApp/foo/someAction.do
DatTT-DSE-SOICT-HUST

24

9/10/2011

Lung Struts (Struts 1.0)

iu khin lung bi Controller

Http://myhost/authorize.do

Server configured to pass *.do extensions to


org.apache.struts.action.ActionServlet via a
web.xml configuration file

ActionServlet object inspects the URI and tries to match it


against an ActionMapping located in the struts-config.xml file

Instance of appropriate Action class is found and its execute()


is called.

DatTT-DSE-SOICT-HUST

Action object handles the request and returns a next view.


View is identified by ActionForward objerct.

25

DatTT-DSE-SOICT-HUST

26

Nhim v ca RequestProcessor?

2.1.2. RequestProcessor
(Framework cung cp)

processPath

processLocale

processMapping

DatTT-DSE-SOICT-HUST

processPopulate

processValidate

processActionForm

Nu mapping c kt hp vi mt role, cn m bo
user c role tng ng . Nu khng, to ra mt error
v dng x l request.

To mt thc th ActionForm (nu cn thit) kt hp vi


mapping trn (nu c), vi tm vc (scope) ph hp

DatTT-DSE-SOICT-HUST

29

28

What Does RequestProcessor Do?

Xc nh ActionMapping ng vi ng dn yu cu.

processRoles

Thit lp content type mc nh (ty chn cch encoding)


cho tt c cc response nu c yu cu

27

What Does RequestProcessor Do?

Chn mt locale (nu cha chn locale no) v t n


vo trong request.

processContent

DatTT-DSE-SOICT-HUST

Xc nh ng dn (path) c request. Sau s c


s dng ly v mt ActionMapping.

Gn ActionForm vi request, nu c
Thc hin validate (nu c yu cu) trn
ActionForm gn vi request ny (nu c).

processForward

Nu mapping biu din mt forward, forward


n ng dn c ch nh trong mapping.

DatTT-DSE-SOICT-HUST

30

9/10/2011

What Does RequestProcessor Do?

processInclude

Nu mapping biu din mt include, include kt


qu ca vic gi n ng dn (path) trong
request ny

processForwardConfig

processActionCreate

What Does RequestProcessor Do?

To mt thc th ca lp c c t trong
ActionMapping ang xt (nu cn).

processActionPerform

Cui cng, phng thc x l ca


RequestProcessor ly v ActionForward tr v t
lp Action, v s dng n chn ra resource
tip theo (nu c).
Thng ActionForward s dn n cc trang
trnh din (presentation page), sinh ra response
tr v cho client.

L lc m phng thc perform() hoc execute()


s c gi
DatTT-DSE-SOICT-HUST

31

DatTT-DSE-SOICT-HUST

32

Action Mapping trong file cu hnh Struts

2.1.3. Action Mapping


(LTV vit)

Struts controller ActionServlet cn bit 1 s


thng tin map mi request URI gi n
vi lp Action ph hp
Cc yu cu ny c ng gi trong mt
Java interface l ActionMapping

DatTT-DSE-SOICT-HUST

DatTT-DSE-SOICT-HUST

33

Struts Config File (struts-config.xml)

<form-beans>

<form-beans> cha cc nh ngha FormBean


bao gm tn v kiu (classname)
<action-mapping> cha cc nh ngha action

34

Struts Config File (struts-config.xml)

struts-config.xml cha 3 phn t quan trng


m t cc actions:

Struts framework s to i tng


ActionMapping cho mi phn t cu hnh
<ActionMapping> trong file struts-config.xml

Phn t ny cha cc nh ngha form bean.


S dng phn t <form-bean> cho mi form
bean, bao gm 2 thuc tnh quan trng sau:

S dng mt phn t <action> cho mi action c


nh ngha

name: the name of the request request (and session


level attribute that this form bean will be stored as)
type: tn lp y ca form bean

<global-forwards> cha c nh ngha global


forward
DatTT-DSE-SOICT-HUST

35

DatTT-DSE-SOICT-HUST

36

9/10/2011

struts-config.xml: <form-beans>

Struts Config File (struts-config.xml)

1.<?xml version="1.0" encoding="ISO-8859-1" ?>

<action-mappings>

2.<!DOCTYPE struts-config PUBLIC


3.
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
4.
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

Phn t ny cha cc nh ngha action. Mi


action cn nh ngha ng vi mt phn t
<action>

5.<struts-config>
6. <!-- ========== Form Bean Definitions ================= -->
7. <form-beans>
8.
9.

<form-bean

name="submitForm"
type="submit.SubmitForm"/>

10. </form-beans>
DatTT-DSE-SOICT-HUST

37

DatTT-DSE-SOICT-HUST

Struts Config File (struts-config.xml)

struts-config.xml: <action-mappings>

<action-mappings>

1.<!-- ========== Action Mapping Definitions ============ -->


2. <action-mappings>

Mi phn t <action> cn nh ngha cc thuc


tnh sau:

3. <action path="/submit"
4.
type="submit.SubmitAction"
5.
name="submitForm"
6.
input="/submit.jsp"
7.
scope="request"
8.
validate="true">
9. <forward name="success" path="/submit.jsp"/>
10. <forward name="failure" path="/submit.jsp"/>
11. </action>

path: ng dn ti action (tng i so vi context


ca ng dng) (URI ca request)
type: Tn y ca lp Action
name: Tn ca phn t <form-bean> s dng vi
action ny
input: Tn ca trang hin th khi c li validate input
form
scope: Tm vc ca form bean c to
validate: C thc DatTT-DSE-SOICT-HUST
hin validate input form hay khng 39

12. </action-mappings>
13.</struts-config>
DatTT-DSE-SOICT-HUST

2.
3.
4.
5.
6.
7.
8.

<action-mappings>

<global-forwards>

<action
path="/logon"
type="org.apache.struts.webapp.example.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp"
validate="true" />

9. </action-mappings>

Forwards l cc thc th ca lp ActionForward


c tr v t phng thc execute() ca lp
Action
Thc hin map cc logical names vi cc
resources c th (thng l cc trang JSPs)
Phn t <forward> c cc thuc tnh sau

10.</struts-config>

name: logical name ca forward

DatTT-DSE-SOICT-HUST

40

Action Mapping Config File

struts-config.xml: <action-mappings>

1.

38

41

c s dng trong phng thc execute() ca lp Action


forward n ti nguyn tip theo

path: resource s c forward n


redirect: redirect DatTT-DSE-SOICT-HUST
(true) hay forward (false)

42

9/10/2011

Global Forwarding

Local Forwarding

1.<struts-config>

1.<!-- Edit mail subscription -->

2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

2.<action
3. path="/editSubscription"
4. type="org.apache.struts.webapp.example.EditSubscriptionAction"
5. name="subscriptionForm"
6. scope="request"
7. validate="false">
8. <forward
9.
name="failure"
10.
path="/mainMenu.jsp"/>
11. <forward
12.
name="success"
13.
path="/subscription.jsp"/>
14.</action>

<form-beans>
<form-bean
name="logonForm"
type="org.apache.struts.webapp.example.LogonForm" />
</form-beans>
<global-forwards
type="org.apache.struts.action.ActionForward">
<forward
name="logon"
path="/logon.jsp"
redirect="false" />
</global-forwards>

DatTT-DSE-SOICT-HUST

43

DatTT-DSE-SOICT-HUST

44

ActionForm Bean (Form bean)


2.1.4. ActionForm
(LTV phi cung cp, nu khng s
dng DynaActionForm)

Vit bi LTV

nh ngha mt ActionForm bean (bn cht l 1 lp Java


k tha lp ActionForm) cho input form
nh ngha trong file struts-config.xml

DatTT-DSE-SOICT-HUST

Ch cha cc phng thc getter & setter cho cc


thuc tnh (khng c x l nghip v)
Cung cp c ch validation chun tc

DatTT-DSE-SOICT-HUST

45

ActionForm Bean & Controller

Kim tra session scope cho 1 thc th ca ActionForm


bean

Ch cn vit phng thc getter v setter cho


mi thuc tnh ca mt input form

Nu khng tn ti, controller s to mi mt thc th

Gi phng thc setter tng ng ca ActionForm bean


cho tt c cc tham s request c tn trng vi tn ca
thuc tnh ca bean
Truyn i tng ActionForm bean lm tham s ca
phng thc execute() ca lp Action

DatTT-DSE-SOICT-HUST

46

Vit mt ActionForm Bean?

Vi mi ActionForm bean c nh ngha trong file


servlet-config.xml, Controller (ActionServlet) s

<form-bean>
Tn thuc tnh ca lp <Action>

47

Khng c bt k on code x l nghip v no

Thm 1 phng thc validate chun tc:


validate()
Controller s gi n phng thc ny

nh ngha mt thuc tnh (cng vi phng


thc getXxx v setXxx) cho mi trng xut
hin trong input form
DatTT-DSE-SOICT-HUST

48

9/10/2011

V d: submit.jsp

1.<%@
2.<%@
3.<%@
4.<%@

page language="java" %>


taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

Model: ActionForm

5.<html>
6.<head><title>Submit example</title></head>
7.<body>

1.package submit;
2.import javax.servlet.http.HttpServletRequest;
3.import org.apache.struts.action.*;

8.<h3>Example Submit Page</h3>

4.public final class SubmitForm extends ActionForm {

9.<html:errors/>
10.<html:form action="submit.do">
11.Last Name: <html:text property="lastName"/><br>
12.Address: <html:textarea property="address"/><br>
13.Sex:
<html:radio property="sex" value="M"/>Male
14.
<html:radio property="sex" value="F"/>Female<br>
15.Married: <html:checkbox property="married"/><br>
16.Age:
<html:select property="age">
17.
<html:option value="a">0-19</html:option>
18.
<html:option value="b">20-49</html:option>
19.
<html:option value="c">50-</html:option>
20.
</html:select><br>
21.
<html:submit/>
DatTT-DSE-SOICT-HUST
22.</html:form>

5. /* Last Name */
6. private String lastName = "Hansen"; // default value
7. public String getLastName() {
8. return (this.lastName);
9. }
10. public void setLastName(String lastName) {
11. this.lastName = lastName;
12. }

49

struts-config.xml: <form-beans>

13. /* Address */
14. private String address = null;
15. public String getAddress() {
16. return (this.address);
17. }
18. public void setAddress(String address) {
19. this.address = address;
20. }
DatTT-DSE-SOICT-HUST
21....

50

struts-config.xml: <action-mappings>

1.<?xml version="1.0" encoding="ISO-8859-1" ?>

2.<!DOCTYPE struts-config PUBLIC


3.
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
4.
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
5.<struts-config>
6. <!-- ========== Form Bean Definitions ================= -->
7. <form-beans>
8.
9.

<form-bean

name="submitForm"
type="submit.SubmitForm"/>

1.<!-- ========== Action Mapping Definitions ============ -->


2. <action-mappings>
3. <action path="/submit"
4.
type="submit.SubmitAction"
5.
name="submitForm"
6.
input="/submit.jsp"
7.
scope="request"
8.
validate="true">
9. <forward name="success" path="/submit.jsp"/>
10. <forward name="failure" path="/submit.jsp"/>
11. </action>
12. </action-mappings>

10. </form-beans>

13.</struts-config>
DatTT-DSE-SOICT-HUST

51

DatTT-DSE-SOICT-HUST

52

DynaActionForm trong Struts 1.1

Thay v to mt lp con cho ActionForm vi


cc phng thc get/set cho mi thuc tnh
ca bean, LTV c th lit k cc thuc tnh
ny, cng vi kiu, gi tr mc nh trong file
cu hnh Struts

2.1.5. Action
(LTV t vit)

NN s dng DanaActionForm khi c th

(Struts nng cao)


DatTT-DSE-SOICT-HUST

53

DatTT-DSE-SOICT-HUST

54

9/10/2011

Action Class Diagram

Lp Action

Tp trung vo lung iu khin

X l client request bng cch gi cch i tng khc


(BusinessLogic beans) trong phng thc execute() ca
n
Tr v mt i tng ActionForward nh danh mt
destination resource m iu khin s c forward n
Destination resource c th l

DatTT-DSE-SOICT-HUST

55

DatTT-DSE-SOICT-HUST

Lp Action l g?

X l request
Thc hin cc x l logic nghip v

Lp action n gin t thc hin x l logic nghip v


Lp action phc tp y quyn cc x l logic nghip v
cho cc thnh phn Model

DatTT-DSE-SOICT-HUST

58

Phng thc execute(..) ca lp Action


(Ch trong Struts 1.1)

K tha org.jakarta.struts.action.Action
Override

Cn vit code lp LogonAction

57

Nhim v ca LTV: Action Class

Xc thc ngi dng


Thit lp User Session
X l li

Chc nng ca lp Action ging nh mu thit k Facade

DatTT-DSE-SOICT-HUST

ng dng cn

C th n gin hoc phc tp

56

V d Action: Logon

Lp Java thc hin cc cng vic trong ng dng

JSP
Tile definition
Velocity template
Action khc

c gi bi controller
public ActionForward execute(
ActionMapping mapping,

Phng thc execute() (trong Struts 1.1)


Phng thc perform() (trong Struts 1.0)

ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception;

DatTT-DSE-SOICT-HUST

59

DatTT-DSE-SOICT-HUST

60

10

9/10/2011

Phng thc perform(..) ca lp Action


(Ch trong Struts 1.0)

Phng thc execute() ca lp Action

Deprecated

public ActionForward perform(


ActionMapping mapping,
ActionForm form,

Thc hin cc x l cn thit vi request


Cp nht cc i tng pha server (Scope
variables) c s dng to trang tr v
cho ngi dng
Tr v i tng ActionForward ph hp

HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException;
DatTT-DSE-SOICT-HUST

61

DatTT-DSE-SOICT-HUST

V d: lp Action

Hng dn thit k lp Action

1.package submit;

2.import javax.servlet.http.*;
3.import org.apache.struts.action.*;
4.public final class SubmitAction extends Action {
5.
6.
7.
8.

public ActionForward execute(ActionMapping mapping,


ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

9.
SubmitForm f = (SubmitForm) form; // get the form bean
10.
// and take the last name value
11.
String lastName = f.getLastName();
12.
// Translate the name to upper case
13.
//and save it in the request object
14.
request.setAttribute("lastName", lastName.toUpperCase());
15.
16.
// Forward control to the specified success target
17.
return (mapping.findForward("success"));
18. }
19.}
DatTT-DSE-SOICT-HUST

Controller Servlet to 1 thc th duy nht


cho lp Action, v s dng n cho tt c cc
request

Lp Action phi hot ng ch multithreaded safe


Ch s dng cc bin local (as opposed to
instanace variables)

Ch nn to cc lp Action n gin

S dng cc thnh phn Model cho cc x l


logic nghip v phc tp

63

V d 2: Lp Action

DatTT-DSE-SOICT-HUST

64

struts-config.xml: ActionMapping

1.package submit;
2.import javax.servlet.http.*;
3.import org.apache.struts.action.*;
4.public final class SubmitAction extends Action {
5. public ActionForward execute(ActionMapping mapping,
6.
ActionForm form,
7.
HttpServletRequest request,
8.
HttpServletResponse response) {
9.
SubmitForm f = (SubmitForm) form; // get the form bean
10.
// and take the last name value
11.
String lastName = f.getLastName();
12.
if (lastName.startsWith(Passion)){
13.
// Translate the name to upper case
14.
//and save it in the request object
15.
request.setAttribute("lastName", lastName.toUpperCase());
16.
// Forward control to the specified success target
17.
return (mapping.findForward("success"));
18.
}
19.
else{
20.
return (mapping.findForward("failure"));
21.
}
22. }
DatTT-DSE-SOICT-HUST
23.}

62

1. <!-- ========== Action Mapping Definitions ============ -->


2. <action-mappings>
3. <action path="/submit"
4.
type="submit.SubmitAction"
5.
name="submitForm"
6.
input="/submit.jsp"
7.
scope="request"
8.
validate="true">
9. <forward name="success" path="/submitSuccess.jsp"/>
10. <forward name="failure" path="/submitFailure.jsp"/>
11. </action>
12. </action-mappings>
65

13.</struts-config>

DatTT-DSE-SOICT-HUST

66

11

9/10/2011

Cc lp Action xy dng sn

ForwardAction
DispatchAction

2.2. Cc thnh phn Model


(Model Components)
(LTV vit)

(Advanced Struts)

DatTT-DSE-SOICT-HUST

67

DatTT-DSE-SOICT-HUST

Model Components

Model components

Model c chia thnh:

Internal state ca h thng


Business logic thay i cc trng thi

Internal state ca h thng c biu din bng:

JavaBeans
Enterprise JavaBeans
POJO's
JDO
JDBC
...
DatTT-DSE-SOICT-HUST

69

DatTT-DSE-SOICT-HUST

Model Components

68

JavaBeans v Scope

Page ch thy trong 1 trang JSP, trong vng i


ca request hin ti
Request ch thy trong 1 trang JSP, cng nh
bt k trang hoc servlet no c included
trong trang JSP ny, hoc c forwarded t n
Session thy c cho tt c cc trang JSP v
cc servlet trong session ca 1 user, trn 1 hoc
nhiu requests
Application thy c cho tt c cc trang JSP
v cc servlets trong
ng dng web
DatTT-DSE-SOICT-HUST
71

70

Model Components

Cc trang JSP v servlets trong cng 1 ng


dng web chia s cng 1 tp cc bean
V d

Servlet code
MyCart mycart = new MyCart(...);
request.setAttribute("cart", mycart);

JSP page
<jsp:useBean id="cart" scope="request"
class="com.mycompany.MyApp.MyCart"/>
DatTT-DSE-SOICT-HUST

72

12

9/10/2011

Cc thnh phn Model trong Struts


Framework

ActionForm Bean

Struts Model Components

SystemState Bean

Lu ActionForm Bean l mt Model component,


mc d n ch biu din d liu nhp bi ngi
dng

System State Bean & Business


logic Bean

Ch l thut ng mc khi nim: Struts khng


cung cp cc API lp trnh

BusinessLogic Bean

Ch l thut ng mc khi nim: Struts khng


cung cp cc API lp trnh
DatTT-DSE-SOICT-HUST

73

DatTT-DSE-SOICT-HUST

System State Bean

System State Bean

Struts khng nh ngha lp chun cho loi bean


ny
Xc nh trng thi hin ti

C th c biu din bi tp mt hoc nhiu cc lp


JavaBeans, cc lp c cc thuc tnh xc nh trng thi
hin ti

Vi h thng quy m nh, ho vi cc thng tin


trng thi (state information) khng cn lu tr lu
di:

V d: h thng gi hng-shopping cart:

75

C th l mt JavaBean thng thng


C th l EJB c trng thi hoc phi trng thi

H thng ln: phng thc nm lun trong cc


beans biu din trng thi h thng
H thng nh: phng thc nm trong cc lp
Action
DatTT-DSE-SOICT-HUST

76

L tng nht l phi c thit k sao cho


chng khng bit mnh c thc thi trn
mi trng Web

ng gi cc functional logic (lm thay i


trng thi h thng) thnh cc phng thc

C th s dng EJB

BuesinessLogic Bean

Struts khng nh ngha lp chun cho loi


bean ny

V d: i tng CustomerBean tng ng vi 1 row no


trong bng CUSTOMERS

DatTT-DSE-SOICT-HUST

BusinessLogic Bean

Cc System state beans c th biu din thng tin c


lu tr lu di trong cc CSDL ngoi

Tp cc system state beans c th cha ton b tri thc


h thng c c

Vi ng dng quy m ln

Cha mt bean tng trng cho gi hng c qun l


c lp cho mi ngi mua hng
Bao gm tp cc items m ngi mua hng chn mua
DatTT-DSE-SOICT-HUST

74

77

Khng nn tham chiu n bt k i tng no


trong ng dng Web
Tng tnh ti s dng

DatTT-DSE-SOICT-HUST

78

13

9/10/2011

View components
2.3. Cc thnh phn View
(View Components)
LTV phi cung cp

DatTT-DSE-SOICT-HUST

DatTT-DSE-SOICT-HUST

79

View Components

View

Cc JSP files cho tng ng dng


Tp cc JSP custom tag libraries
Cc Resource files cho tnh nng
internationalization
Cho php nhanh chng to form cho cc ng
dng
Phi hp hot ng vi controller Servlet

i tng ActionForward thng bo vi


Servlet controller trang JSP no s c tr
v (dispatched)
Cc trang JSP s dng ActionForm ly d
liu output t Model hin th
Struts c tp cc th vin th (tag libraries)

DatTT-DSE-SOICT-HUST

5.<html>
6.<head><title>Submit example</title></head>
7.<body>

<input type="text" name="username"


value="<%= loginBean.getUsername() >"/>

8.<h3>Example Submit Page</h3>


9.<html:errors/>

<html:text property="username"/>;

DatTT-DSE-SOICT-HUST

82

V d: submit.jsp

Vi Struts, ch cn

DatTT-DSE-SOICT-HUST

1.<%@ page language="java" %>


2.<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
3.<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
4.<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

Nu user gy li (vd: nhp liu), ng dng


cn cho php h sa i li gi tr c
Vi JSP:

D pht trin cc ni dung ng


n gin trao i gia HTML designer v LTV

81

Forms v FormBean Interactions

80

83

10.<html:form action="submit.do">
11.Last Name: <html:text property="lastName"/><br>
12.Address: <html:textarea property="address"/><br>
13.Sex:
<html:radio property="sex" value="M"/>Male
14.
<html:radio property="sex" value="F"/>Female<br>
15.Married: <html:checkbox property="married"/><br>
16.Age:
<html:select property="age">
17.
<html:option value="a">0-19</html:option>
18.
<html:option value="b">20-49</html:option>
19.
<html:option value="c">50-</html:option>
20.
</html:select><br>
21.
<html:submit/>
DatTT-DSE-SOICT-HUST
22.</html:form>

84

14

9/10/2011

V d: submit.jsp
1.<logic:present name="lastName" scope="request">
2.Hello
3.<logic:equal name="submitForm" property="age" value="a">
4. young
5.</logic:equal>
6.<logic:equal name="submitForm" property="age" value="c">
7. old
8.</logic:equal>
9.<bean:write name="lastName" scope="request"/>
10.</logic:present>

3. web.xml

11.</body>
12.</html>

DatTT-DSE-SOICT-HUST

85

Web App Deployment Descriptor


(web.xml)

1.<!DOCTYPE web-app
2. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
3. "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

Tun th theo lut chung


Phi c file deployment descriptor - web.xml

web.xml cha:

Cu hnh mapping cho ActionServlet


nh ngha Resource file trong <init-param>
Ch nh file servlet-config.xml trong <init-param>
nh ngha cc th vin th Struts

web.xml c lu tr trong WEB-INF/web.xml


DatTT-DSE-SOICT-HUST

86

V d: web.xml

ng dng Struts l mt ng dng Web

DatTT-DSE-SOICT-HUST

87

4.<web-app>
5. <display-name>Advanced J2EE Programming Class Sample App</display-name>
6.
7. <!-- Standard Action Servlet Configuration (with debugging) -->
8. <servlet>
9. <servlet-name>action</servlet-name>
10. <servlet-class>
11. org.apache.struts.action.ActionServlet
12. </servlet-class>
13. <init-param>
14.
<param-name>application</param-name>
15.
<param-value>ApplicationResources</param-value>
16. </init-param>
17. <init-param>
18.
<param-name>config</param-name>
19.
<param-value>/WEB-INF/struts-config.xml</param-value>
20. </init-param>
21.</servlet>
DatTT-DSE-SOICT-HUST
88

V d: web.xml
1. <!-- Standard Action Servlet Mapping -->
2. <servlet-mapping>
3. <servlet-name>action</servlet-name>
4. <url-pattern>*.do</url-pattern>
5. </servlet-mapping>
6.
7. <!-- Struts Tag Library Descriptors -->
8. <taglib>
9. <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
10. <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
11. </taglib>
12. <taglib>
13. <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
14. <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
15. </taglib>
16. <taglib>
17. <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
18. <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
19. </taglib>
20.</web-app>

DatTT-DSE-SOICT-HUST

4. Internationalization

89

DatTT-DSE-SOICT-HUST

90

15

9/10/2011

Internationalization

M rng ca java.util.ResourceBundle

org.apache.struts.util.MessageResources

Internationalization: Nhim v ca LTV

Ch gii hn h tr hin th. Nhp liu ty


theo thit b client
Cu hnh resource bundles trong web.xml file

To resource file cho ngn ng mc nh


To cc resource files cho mi ngn ng
mun h tr
nh ngha tn ca cc resource nh cc
tham s khi to
Trong trang JSP

DatTT-DSE-SOICT-HUST

91

Resource files

3.error.lastName=<li>Enter your last name


4.error.address=<li>Enter your address
5.error.sex=<li>Enter your sex
6.error.age=<li>Enter your age

prompt.hello=Hello

MyApplication_xx.properties

92

1.errors.header=<h4>Validation Error(s)</h4><ul>
2.errors.footer=</ul><hr>

Cha thng ip vit bng ngn ng mc nh


Mi thng ip c dng (vd Ting Anh):

DatTT-DSE-SOICT-HUST

V d: ApplicationResource.properties

MyApplication.properties

S dng <html:errors/> hin th cc thng


bo li theo locale

Cha cng thng ip tng ng, nhng


cc ngn ng khc, c m ngn ng theo chun
ISO l "xx"

prompt.hello=Bonjour
DatTT-DSE-SOICT-HUST

93

DatTT-DSE-SOICT-HUST

94

V d: web.xml
1. <servlet>
2. <servlet-name>action</servlet-name>
3. <servlet-class>
4. org.apache.struts.action.ActionServlet
5. </servlet-class>
6. <init-param>
7.
<param-name>application</param-name>
8.
<param-value>
9.
com.mycompany.mypackage.MyApplication
10. </param-value>
11. </init-param>
12. <!-- ... -->
13.</servlet>

DatTT-DSE-SOICT-HUST

5. (Input) Validation

95

DatTT-DSE-SOICT-HUST

96

16

9/10/2011

validate() method

Validation: Nhim v ca LTV (Struts 1.0)

Ch nh s thc hin validate input bng thuc tnh


validate ca phn t <action> (con ca phn t
<action-mapping>) trong file servlet-config.xml

Ty chn

C php:

input=/errorpage.jsp

DatTT-DSE-SOICT-HUST

Cn m bo nhp ng thi c username v


password
Cn m bo password c t nht l 6 k t

Sau khi thc hin validate

Nu khng xy ra li validate no, tr v null


Nu xy ra li validate, tr v 1 thc th ca lp
ActionErrors

DatTT-DSE-SOICT-HUST

DatTT-DSE-SOICT-HUST

100

struts-config.xml: Validation

L c ch c s dng tr v cc li khi
thc hin validate input
ng gi li cc li

Mi ActionError cha kha thng ip li (error message key)


trong MessageResources bundle ca ng dng
Controller servlet lu tr mng ActionErrors nh 1 thuc tnh
request s dng cho cc th <html:errors>
Controller sau forwards iu khin t li input form (xc nh
trong thuc tnh input ho Actionmapping tng ng)

99

Lp ActionError

98

Phng thc validate()

Trong ng dng Login

public ActionErrors validate(ActionMapping mapping,


HttpServletRequest request);

97

V d: phng thc validate()

Phng thc mc nh tr v null

Ty chn
DatTT-DSE-SOICT-HUST

Sau khi ly xong cc thuc tnh ca bean


Nhng trc khi phng thc execute() ca lp Action
tng ng c gi

Override phng thc validate() trong lp


ActionForm

c gi bi controller servlet

validate=true

Ch nh trang JSP cn c hin th khi validation


khng thnh cng

Cc message key c s dng tm kim ra


message text ph hp t cc resource file

ActionErrors l mt tp cc ActionError

1. <!-- ========== Action Mapping Definitions ============ -->


2. <action-mappings>
3. <action path="/submit"
4.
type="hansen.playground.SubmitAction"
5.
name="submitForm"
6.
input="/submit.jsp"
7.
scope="request"
8.
validate="true">
9. <forward name="success" path="/submit.jsp"/>
10. <forward name="failure" path="/submit.jsp"/>
11. </action>
12. </action-mappings>

DatTT-DSE-SOICT-HUST

101

13.</struts-config>

DatTT-DSE-SOICT-HUST

102

17

9/10/2011

ActionForm

V d: submit.jsp
1.<%@ page language="java" %>
2.<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
3.<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
4.<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

1.public final class SubmitForm extends ActionForm {


2.
3....
4. public ActionErrors validate(ActionMapping mapping,
5.
HttpServletRequest request) {
6. ...
7.
8. // Check for mandatory data
9. ActionErrors errors = new ActionErrors();
10. if (lastName == null || lastName.equals("")) {
11.
errors.add("Last Name", new ActionError("error.lastName"));
12. }
13. if (address == null || address.equals("")) {
14.
errors.add("Address", new ActionError("error.address"));
15. }
16. if (sex == null || sex.equals("")) {
17.
errors.add("Sex", new ActionError("error.sex"));
18. }
19. if (age == null || age.equals("")) {
20.
errors.add("Age", new ActionError("error.age"));
21. }
22. return errors;
23. }
24...
DatTT-DSE-SOICT-HUST
25.}

5.<html>
6.<head><title>Submit example</title></head>
7.<body>
8.<h3>Example Submit Page</h3>
9.<html:errors/>
10.<html:form action="submit.do">
11.Last Name: <html:text property="lastName"/><br>
12.Address: <html:textarea property="address"/><br>
13.Sex:
<html:radio property="sex" value="M"/>Male
14.
<html:radio property="sex" value="F"/>Female<br>
15.Married: <html:checkbox property="married"/><br>
16.Age:
<html:select property="age">
17.
<html:option value="a">0-19</html:option>
18.
<html:option value="b">20-49</html:option>
19.
<html:option value="c">50-</html:option>
20.
</html:select><br>
21.
<html:submit/>
DatTT-DSE-SOICT-HUST
22.</html:form>

103

104

Validator Framework trong Struts 1.1

Validation logic c th c m t trong file


cu hnh struts-config.xml

6. X l li (Error Handling)

Thay v phi vit code phng thc Java:


validate()

(Struts nng cao)

DatTT-DSE-SOICT-HUST

105

DatTT-DSE-SOICT-HUST

CustomExceptionHandler (1.1)

T nh ngha lp ExceptionHandler, c
gi n khi phng thc execute() ca 1
Action nm ra 1 Exception

ExceptionHandler t nh ngha (1.1)

Cu hnh b x l ngoi l trong strutsconfig.xml


<global-exceptions>
<exception
key="some.key"
type="java.io.IOException"

L lp con ca
org.apache.struts.action.ExceptionHandler
Phng thc execute() phi x l Exception v
tr v 1 i tng ActionForward thng bo
vi Struts s forward n u tip

handler="com.yourcorp.ExceptionHandler"/>
</global-exceptions>

DatTT-DSE-SOICT-HUST

106

107

com.yourcorp.ExceptionHandler.execute() s
c gi khi c bt k mt IOException no
c nm ra bi mt
Action
DatTT-DSE-SOICT-HUST
108

18

9/10/2011

CustomExceptionHandler (1.1)

1.package hansen.playground;
2.import javax.servlet.http.*;
3.import org.apache.struts.action.*;
4.public final class SubmitAction extends Action {
5. public ActionForward execute(ActionMapping mapping,
6.
ActionForm form,
7.
HttpServletRequest request,
8.
HttpServletResponse response) {

C th c tc dng global hoc cho tng


action

<action ...>
<exception
key="some.key"
type="java.io.IOException"
handler="com.yourcorp.ExceptionHandler"/>
</action>
DatTT-DSE-SOICT-HUST

V d: nm ra mt Exception

109

9.
SubmitForm f = (SubmitForm) form; // get the form bean
10.
// and take the last name value
11.
String lastName = f.getLastName();
12.
if (lastName.startsWith(Passion)){
13.
// Translate the name to upper case
14.
//and save it in the request object
15.
request.setAttribute("lastName", lastName.toUpperCase());
16.
// Forward control to the specified success target
17.
return (mapping.findForward("success"));
18.
}
19.
else{
20.
throw new WrongLastNameExcetion(lastName);
21.
}
22. }
DatTT-DSE-SOICT-HUST
23.}

110

ExceptionHandler t nh ngha (1.1)

Cc ExceptionHandler khc nhau cho cc li


khc nhau

<global-exceptions>
<exception handler=
"com.cavaness.storefront.CustomizedExceptionHandler"
key="global.error.message"
path="/error.jsp"
scope="request"
type="java.lang.Exception"/>
<exception handler=
"com.cavaness.storefront.SecurityExceptionHandler"
key="security.error.message"
path="/login.jsp"
scope="request"
type="com.cavaness.storefront.SecurityException"/>
DatTT-DSE-SOICT-HUST
111
</global-exceptions>

112

Trong file struts-config ,

DatTT-DSE-SOICT-HUST

struts-config.xml: ActionMapping

View Selection: Nhim v ca LTV

7. View Selection

Vi mi outcome (gi tr ca thuc tnh name ca


th <forward>), ch nh trang JSP s c
forward ti nh th con <forward>, con ca th
<action> hoc th <global-forwards>

Trong phng thc execute() ca lp Action,

Tr v i tng ActionForward, ng vi
outcome no.

1. <!-- ========== Action Mapping Definitions ============ -->


2. <action-mappings>
3. <action path="/submit"
4.
type="hansen.playground.SubmitAction"
5.
name="submitForm"
6.
input="/submit.jsp"
7.
scope="request"
8.
validate="true">
9.
<forward name="success" path="/submit.jsp"/>
10.
<forward name="failure" path="/submit.jsp"/>
11. </action>
12. </action-mappings>

DatTT-DSE-SOICT-HUST

113

13.</struts-config>

DatTT-DSE-SOICT-HUST

114

19

9/10/2011

V d: Action Class
1.package hansen.playground;
2.import javax.servlet.http.*;
3.import org.apache.struts.action.*;
4.public final class SubmitAction extends Action {
5.
6.
7.
8.

public ActionForward execute(ActionMapping mapping,


ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

9.
SubmitForm f = (SubmitForm) form; // get the form bean
10.
// and take the last name value
11.
String lastName = f.getLastName();
12.
// Translate the name to upper case
13.
//and save it in the request object
14.
request.setAttribute("lastName", lastName.toUpperCase());
15.
16.
// Forward control to the specified success target
17.
return (mapping.findForward("success"));
18. }
19.}
DatTT-DSE-SOICT-HUST

115

20

You might also like