You are on page 1of 38

Contents

Gii thiu ........................................................................................................................................................ 1

Pluggability of other MVC implementations ..................................................................................... 2

Features of Spring Web MVC .................................................................................................................. 2


3.1

Spring WebFlow ................................................................................................................................... 2

3.2

DispatcherServlet ................................................................................................................................ 4

3.3

Controllers........................................................................................................................................... 10

3.3.1

AbstractController and WebContentGenerator ........................................................... 11

3.3.2

Nhng controller n gin khc ........................................................................................ 12

3.3.3

MultiActionController ............................................................................................................ 12

3.3.4

Lnh ca cc controller ( command controller ) ......................................................... 15

3.4

Handler mappings ............................................................................................................................ 17

3.5

Views. .................................................................................................................................................... 18

3.5.1

Chaining ViewResolvers ........................................................................................................ 18

3.5.2

Redirecting to views ............................................................................................................... 19

3.6

S dng locales .................................................................................................................................. 19

3.6.1

AcceptHeaderLocaleResolver ............................................................................................. 20

3.6.2

CookieLocaleResolver ............................................................................................................ 20

3.6.3

SessionLocaleResolver........................................................................................................... 21

3.6.4

LocaleChangeInterceptor ..................................................................................................... 21

3.7

S dng themes ................................................................................................................................ 21

3.7.1

Gii thiu ..................................................................................................................................... 21

3.7.2

nh ngha themes ................................................................................................................... 21

3.7.3

Theme resolvers ....................................................................................................................... 22

3.8

Multipart support ca Spring (fileupload) ............................................................................. 23

3.8.1

Introduction ............................................................................................................................... 23

3.8.2

Using the MultipartResolver ............................................................................................... 23

3.8.3

Handling a file upload in a form ......................................................................................... 23

3.9

Using Spring's form tag library ................................................................................................... 27

3.9.1

Configuration ............................................................................................................................. 27

3.9.2

Form tag ...................................................................................................................................... 27

3.9.3

Input tag ...................................................................................................................................... 29

3.9.4

Checkbox tag .............................................................................................................................. 29

3.9.5

Radiobutton tag ........................................................................................................................ 30

3.9.6

Password tag ............................................................................................................................. 30

3.9.7

Select tag ..................................................................................................................................... 31

3.9.8

Option tag.................................................................................................................................... 31

3.9.9

Options tag ................................................................................................................................. 32

3.9.10

The textarea tag ................................................................................................................... 32

3.9.11

The hidden tag ...................................................................................................................... 33

3.9.12

Errors tag ................................................................................................................................ 33

Spring MVC yahoo : ken_uit_9x@yahoo.com


1 Gii thiu
Spring's Web MVC framework c thit k xung quanh mt DispatcherServlet t,n gi
cc request n cc handler, vi vic cho php cu hnh cc handler mapping, view
resolution, locale and theme resolution nh l s h tr tt nht cho vic upload file.
Hanler mc nh rt n gin Controller interface, ch a ra mt phng thc
ModelAndView handleRequest(request,response). Ci ny c th c s dng cho cc
controller ca ng dng, nhng s thch hn khi bao gm kin trc thc thi c th bc, s
nht qun, v d AbstractController, AbstractCommandController and
SimpleFormController. Cc controller ca ng dng s l cc lp con tiu biu ca chng .
Ch rng chng ta c th chn mt lp c s nu chng ta khng c mt form, chng ta
khng cn mt form controller. y l iu khc bit chnh so vi Strusts.
Spring Web MVC cho php chng ta s dng vi i tng nh l mt lnh hoc i tng
form khng cn implement mt framework-specific interface hoc base class. Spring's
data binding c tnh mm do cao: v d, n i x cc kiu khng hp nh l cc
validation error, iu ny c th c c lng bi ng dng, khng nh cc system
error. Vi tt c nhng iu ny c ngha l chng ta khng cn sao chp cc property ca
i tng bussiness, khng cn phi g cc chui vo trong form i tng ch x l yu
cu khng ph hp, hoc chuyn i thnh cc chui. Thay vo n thng a ra s lin
kt trc tip n i tng business ca chng ta. y l im khc bit chnh so vi Struts,
Strust c xy dng xung quanh yu cu cc lp c s nh l Action v ActionForm.
So snh vi WebWork , spring c thm cc vai tr khc ca i tng. N h tr th s
thng bo ca mt controller, mt lnh ty chn hoc mt i tng form, v mt m hnh
thng n view. M hnh s n gin bao gm lnh v i tng form nhng cng c d
liu lin quan ty ; Thay vo , mt WebWork Action kt hp tt c nhng vai tr vo
trong mt i tng ring r. WebWork cho pho bn s dng nhng i tng business
ca form, nhng ch lm cc thuc tnh bean cho cc lp Action tng ng. Cui cng,
nhng th hin Action ging nhau, s x l request ca n c s dng cho vic nh gi
v xa nh v tr ca form trong View. Nh vy, d liu lin quan cng cn c m hnh
nh cc thuc tnh bean ca Action. Vi nhng th nh vy, ngi ta c th cho rng c qu
nhiu vai tr cho mt i tng.
Gii php view ca Spring mm do v cng. Mt s thc thi ca mt Controller c th
thm chi c th ghi mt view trc tip vo response ( bng cch tr v gi tr null null cho
ModelAndView). Trong trng hp n gin, mt th hin ModelAndView bao gm mt
tn ca view v mt m hnh nh x(Map), n cha ng tn bean v nhng i tng
tng ng (going mt lnh hoc mt form, cha ng d liu lin quan). Gii php dng
tn view c th c cu hnh tt, hoc thng qua tn bean, mt file properties, hoc qua
thng ViewResolver implementation ca bn. Tht s, m hnh (Min MVC) c da trn
Page 1

Spring MVC yahoo : ken_uit_9x@yahoo.com


Map interface, n cho php cc cng ngh view hon ton tru tng. Mt vi renderer c
th c tch hp trc tip, nh l JSP, Velocity. M hnh Map c chuyn i mt cch
n gin thnh mt nh dng thch hp, nh l cc thuc tnh JSP request hoc mt mu
Velocity.

2 Pluggability of other MVC implementations


C mt vi l do ti sao vi d n thch s dng nhng MVC implement khc. Nhiu nhm
Nhiu nhm pht trin mun nng cp nhng hng tng hin ti gm cc k nng v cng
c. Hn na, c mt lng ln ngi hiu bit v c kinh nghim v Strusts framework.
Tuy nhin, nu bn quen vi kin trc Struts, n vn c th l mt la chn vng chc cho
web layer; cng mt kiu p dng cho WebWork v nhng web MVC framework khc.
Nu bn khng mn s dng Spring's web MVC, nhng c nh s dng nhng gii php
khc m Spring ngh, bn c th tch hp s la chn web MVC framework ca bn vi
Spring mt cch d dng. n gin l khi ng mt Spring root application context thng
qua ContextLoaderListener ca n, v truy cp n thng qua thuc tnh ServletContext ca
n (or hoc phng thc helper ca Spring tng ng) t bn trong mt Struts hoc
WebWork action. Ch , khng c mt vi "plugins" c gi, v th khng c s tch hp c
tnh chuyn mn no l cn thit. T im nhn ca web layer, bn s s dng mt cch n
gin Spring nh l mt th vin, vi th hin root application context nh l mt entry
point(li vo).
Tt c nhng bean bn ng k v cc service ca Spring c th l cc u ngn tay ca
bn thm ch khng c Spring MVC. Spring khng cnh tranh vi Struts or WebWork trong
trng hp ny, n ch xc nh a ch nhiu khu vc ni m s trong sch ca web MVC
frameworks khng lm, T s cu hnh bean n truy cp d lieu v giao tc, x l giao tc.
V th bn c th lm giu ng dng ca mnh vi Spring middle tier hoc/v data access
tier, thm ch nu bn ch mun dng, v d nh, transaction abstraction vi JDBC hoc
Hibernate.

3 Features of Spring Web MVC


3.1 Spring WebFlow
Mc ch Spring Web Flow (SWF) l tm gii php tt nht cho vic qun l lung ca trang
ng dng web ( web application page flow).
SWF tch hp vi cc framework ang tn ti nh Spring MVC, Struts, v JSF, trong c mi
trng. Nu bn c mt business process (hoc processes), n c t khi m mt m hnh
giao tip nh l b i nghch thnh mt m hnh request mt cch r rng, SWF c th l
mt gii php.
Page 2

Spring MVC yahoo : ken_uit_9x@yahoo.com


SWF cho php bn bt cc lung logic ca page nh self-contained modules m n c s
dng li trong cc hon cnh khc, v nh l tng cho vic xy dng cc module ca ng
dng web, n hng dn ngi dng xuyn sut iu khin cc navigation, nhng
navigation ny iu khin business processes.
Tham kho thm v SWF ti trang Spring WebFlow site.
Cc module ca Spring web cung cp mt s phong ph cc feature duy nht cho web, bao
gm:

Phn chia r rng cc vai tr ca controller (roles controller), validator, command


object, form object, model object, DispatcherServlet, handler mapping, view
resolver, etc. Mi vai tr c th c tha mn y bi mt i tng chuyn
dng..
Mnh m v s cu hnh khng phc tp ca c framework v cc lp ng dng
(application classes) nh cc JavaBean, bao gm d dng tham kho (referencing)
thng qua cc context, Chng hn nh t cc web controller n cc i tng
business (business object) v validators.
Kh nng thch ng, khng xm phm (non-intrusiveness). S dng bt c
controller subclass g bn cn (plain, command, form, wizard, multi-action, hoc
mt custom controller) cung cp mt kch bn thay vo thu c t mt
controller n c cho mi th.
Nhng business code c th c s dng li - khng cn phi sao chp. Bn c th
s dng nhng business object nh l lnh (command) hoc form object thay v
phn nh chng theo m rng mt base class framework c bit.
Binding v validation c th chnh sa c nhng s khng ph hp kiu (type
mismatches) nh l application-level validation errors, n gi nhng gi tr li,
localized date v number bindingv.v Thay v ch l String form objects vi s phn
tcch v chuyn i thnh business object bng tay.
Handler mapping c th ty chnh v s gii quyt bng view Cc chin lc
handler mapping v s gii quyt bng view nhm sp xp URL-based n gin
thnh phc tp, cc chin lc cho mc ch xy dng. iu ny lm cho n mm
do hn nhng web MVC framework khch This is more flexible than some web
MVC frameworks.
Tnh linh ng ca model transfer - model transfer thng qua tn/gi tr Map h tr
cho vic d dng tch hp vi mt vi cng ngh view khc.
Locale c th chnh sa v s gii quyt bng theme, h tr cho JSP vi th vin th
ca Spring hoc khng, h tr cho JSTL, h tr cho Velocity khng cn thit phi c
mt cy cu bc qua cng ngh ny, v.v.

Page 3

Spring MVC yahoo : ken_uit_9x@yahoo.com

Mt th vin tag JSP cn mnh m c bit nh l th vin tag Spring, n cung cp


s h tr cho cc tnh nng nh l data binding v themes. Cc tag t do c cho
php ti a trong gii hn m nh du(markup). Tm hiu thm tag th vin tag ti
Appendix D, spring.tld
Mt th vin tag JSP form c gii thiu trong Spring 2.0, n lm cho vic son
tho cc form trong trang JSP d dng hn. Tm hiu thm ti Appendix E, springform.tld
Lifecycle ca lifecycle is c xc nh trong HTTP request hin ti hoc HTTP
Session. y khng phi l c tnh ca Spring MVC, nhng thch
WebApplicationContext container(s) hn, Spring MVC s dng. Tm hiu thm ti
Section 3.4.4, The other scopes

3.2 DispatcherServlet
Spring's web MVC framework ging nh nhiu web MVC frameworks, request-driven, c
thit k xung quanh mt servlet trung tm, n gi cc request n cc controller v a ra
nhng chc nng d dng cho s pht trin ca ng dng web. Spring DispatcherServlet
bt c nh th no , lm nhiu hn l ch c vy. N hon ton c tch hp vi Spring IoC
container v nh vy cho php bn s dng bt c c tnh no m Spring c.
Lung x l request ca Spring Web MVC DispatcherServlet c minh ha trong lc
bn di. Ngi c c hiu bit v m hnh s nhn thy rng that the DispatcherServlet l
mt s din t ca mu thit k Front Controller (y l mt mu m Spring Web MVC
chia s vi nhiu web frameworks dn u khc ).

Page 4

Spring MVC yahoo : ken_uit_9x@yahoo.com

DispatcherServlet l mt Servlet tht (n k tha t lp c s HttpServlet ), v nh vy


c khai bo trong web.xml ca ng dng web ca bn. Nhng request m bn mun
DispatcherServlet x l s c nh x, s dng mt URL mapping trong cng file web.xml.
y l chun cu hnh ca J2EE servlet; mt v d nh l mt s khai bo ca
DispatcherServlet v mapping c th c tm thy bn di.
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servletclass>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
</web-app>

Trong v d trn, tt c cc request kt thc vi .form s c x l bi 'example'


DispatcherServlet. y ch l bc khi u cu hnh trong s thit lp Spring Web
Page 5

Spring MVC yahoo : ken_uit_9x@yahoo.com


MVC...Nhng bean khc nhau c s dng bi Spring Web MVC framework (trn v
DispatcherServlet trn ca chnh n) cu c cu hnh ngay.
Nh c din t chi tit trong phn Section 3.8, The ApplicationContext, nhng th hin
ApplicationContext trong Spring c th c xc nh phm vi. Trong web MVC framework,
mi DispatcherServlet c WebApplicationContext ca chnh n, n k tha tt c cc bean
c nh ngha trong root WebApplicationContext. Nhng th ny c k tha t cc
bean c nh ngha sn, cc bean ny c th b overridden trong phm vi servlet r rng,
v mt phm vi r rng ca cc bean c th c nh ngha sn local cho th hin ca
servlet .

H thng ng cnh Spring Web MVC


Framework s, trn s khi to ca mt DispatcherServlet, tm kim mt tn file [servletname]-servlet.xml trong th mc WEB-INF ca ng dng web ca bn v to cc bean
c nh ngha (overriding nhng s nh ngha ca mt vi bean c nh ngha
cng tn trong phm vi global).
Cn nhc cc DispatcherServlet servlet sau (trong file 'web.xml)
<web-app>

Page 6

Spring MVC yahoo : ken_uit_9x@yahoo.com


...
<servlet>
<servlet-name>golfing</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servletclass>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>golfing</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

Vi v tr trong s cu hnh servlet trn, bn s cn c mt file gi l '/WEB-INF/golfingservlet.xml' trong ng dng ca bn; file ny s cha ng tt c cc m t ca cc
component(bean) ca Spring Web MVC. V tr chnh xc ca cc file cu hnh c th b thay
i qua mt tham s khi to ca servlet ( Xem bn di r hn).
WebApplicationContext l mt s m rng ca plain ApplicationContext, n c mt vi tnh
nng ph cn thit cho cc web. N khc vi mt ApplicationContext bnh thng, n
c kh nng gii quyt cc theme (xem Section 13.7, Using themes), v rng n bit serlet
no n c lin kt (bi c mt lin kt ti ServletContext). WebApplicationContext c
bao bn trong ServletContext, v s dng nhng phng thc tnh trn lp
RequestContextUtils, bn c th lun lun tm thy WebApplicationContext trong trng
hp bn cn truy cp n n.
Spring DispatcherServlet c mt s ghp ni vi cc bean c bit, n dng c th x l
cc request v to ra nhng view thch hp. Nhng bean c bao gm bn trong
Spring framework v c th c cu hnh trong WebApplicationContext, ch nh mt vi
bean khc cn c cu hnh. Mi ci bean ny c m t chi tit hn bn di. By gi,
chng ta s ch cp n chng, va bn bit chng tn ti v c th cho php chng ta
ni v DispatcherServlet. Hu ht cc bean, c th thy c mc nh c cung cp v th
bn khng (initially) phi lo lng v lm sao cu hnh chng.
Table 13.1. S c t bean trong the WebApplicationContext
Bean type

Explanation

Controllers

Controllers l cc thnh phn c to thnh t phn 'C' ca MVC.

Handler
mappings

Handler mappings x l s thc thi ca mt danh sch cc pre- v postprocessors v cc controllers s c thc thi nu chng hp vi tiu
chun chc chn ( cho i tng mt s xng hp ca mt URL c bit
Page 7

Spring MVC yahoo : ken_uit_9x@yahoo.com


Bean type

Explanation
vi controller)

View resolvers

View resolvers l cc thnh phn c kh nng gii quyt cc tn view n


cc view

Mt locale resolver l mt thnh phn c kh nng gii quyt v tr mt


Locale resolver client l ang s dng, c th a n tnh quc t ha cc view
(internationalized view)
Theme resolver

Mt theme resolver c kh nng gii quyt cc theme, ng dng dng


web ca bn c th dng, v d, a n s c nhn ha layout

multipart file
resolver

Mt multipart file resolver a ra cc chc nng x l file upload t


HTML form

Handler
exception
resolver(s)

Handler exception resolvers a ra chc nng nh x cc ngoi l n cc


views hoc thc hin cc x l ngoi l phc tp hn.

Khi mt DispatcherServlet c ci t cho vic s dng v mt request n


DispatcherServlet t bit, ngi ta bo rng DispatcherServlet bt u x l cc request.
Danh sch cc m t sau m t y mt request n khi c s l bi mt
DispatcherServlet:
1. WebApplicationContext c tm kim v bao trong request nh mt thuc tnh cho
controller v nhng nguyn t khc trong qu trnh x l s dng. N c bao mc
nh di t kha DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.
2. V tr ca locale resolver c bao vi request cc nguyn t trong trong qu trnh
x l gii quyt locale s dng khi x l request (to view, chun b d liu,v.v..) nu
bn khng s dng resolver, n s khng gy nh hng g c, v th nu bn khng cn
locale gii quyt , bn khng phi x dng n.
3. Theme resolver c bao vi request cc yu t nh l cc views xc inh theme
no c s dng. Theme resolver khng nh g c nu bn khng dng n, v th bn
khng cn theme th ch cn bn lm ng vi n.
4. Nu mt multipart resolver c c t, request c duyt cho cc multipart; nu cc
multipart c tm thy, request c bao ph trong mt MultipartHttpServletRequest
Page 8

Spring MVC yahoo : ken_uit_9x@yahoo.com


cho qu trnh x l xa hn na bi cc yu t bn trong x l. (Xem Section 13.8.2, Using
the MultipartResolver thm thng tin v multipart handling).
5. Mt handler thch hp c tm kim. Nu mt handler c tm thy, s x l buc lin
kt vi handler (cc preprocessor, cc postprocessor, v controller) s c thc thi
chun b mt a model (cho s pht sinh [render]).
6. Nu mt model c tr v, view c pht sinh (render). Nu khng c m hnh no
c tr v (ci c th c quy vo mt pre- or postprocessor, phn hoch request, v
d, cho l do bo mt), khng c view c pht sinh (render), t khi request c th
c y .
Nhng ngoi l c qung ra trong qu trnh x l request nhn c mt cch tnh c bi
mt vi handler exception resolver m chng c khai bo trong WebApplicationContext.
S dng nhng exception resolver cho php bn nh ngha nhng hnh vi mt cch ty
bin trong trng hp nh cc exception c c bi s qung nm.
Spring DispatcherServlet cng h tr tr v last-modification-date, nh l c c t bi
Servlet API. Tin trnh ca s xc nh ngy chnh sa cui cng cho mt request c bit
th khng phc tp: DispatcherServlet s tm kim mt handler mapping thch hp v kim
th nu handler c tm thy interface implements the interface LastModified. Nu th, gi
tr ca phng thc getLastModified(request) ca interface LastModified c tr v cho
client.
Bn c th ty chnh Spring's DispatcherServlet bng cch thm cc tham s context vo file
web.xml hoc s khi to cc tham s ca servlet. Nhng kh nng c th c lit k nh
sau.
Table 13.2. S khi to cc tham s DispatcherServlet.

Parameter

contextClass

Explanation
Lp thc thi ApplicationContext, n s c dng khi
to ng cnh c s dng bi servlet ny. Nu tham s ny
khng c c t, XmlWebApplicationContext s c s
dng.

String c chuyn n ng cnh ca th hin (context


instance) (c c t bi contextClass) ch ra ni
contextConfigLocation context(s) c th c tm thy. Chui c kh nng phn chia
thnh nhiu chui ( s dng mt du phy tch) h tr
cho nhiu context (trong trng hp nhiu khu vc ca
Page 9

Spring MVC yahoo : ken_uit_9x@yahoo.com


Parameter

Explanation
context, ca cc bean c nh ngha hai ln, ci sau cng
c u tin).

namespace

namespace ca WebApplicationContext. Mc inh l [servletname]-servlet.

3.3 Controllers
S thng bo ca mt controller l mt phn trong thit k ca m hnh MVC (Chnh xc
hn n l 'C' trong MVC. Cc Controller cung cp ch truy cp vo ng dng m n c
nh ngha tiu biu bi mt service interface. Cc Controller gii thch user input v
chuyn i thnh dng input c th hiu c m n s c trnh din cho user bng
view. Spring thc thi s thng bo ca mt controller trong mt cch chung chung tru
tng, cho php mt lng ln cc loi controller c tao to ra. Spring cha ng c t
form (form-specific) ca cc controller, cc command-based controller, v cc controller
m n thc hin wizard-style logic, thnh tn nhng mt t.
C s ca Spring cho kin trc controller l interface
org.springframework.web.servlet.mvc.Controller, Source code cho n c lit k bn di.
public interface Controller {
/**
* Process the request and return a ModelAndView object which the
DispatcherServlet
* will render.
*/
ModelAndView handleRequest(
HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
Nh bn c th thy, Controller interface nh ngha mt phng thc n c chu trch
nhim cho vic x l mt request v tr v mt model v view thch hp. Ba khi nim l
c s cho Spring MVC implementation - ModelAndView v Controller. Trong khi Controller
interface l kh tru tng, Spring a ra mt lng cc Controller implementation c th
s dng d dng v n cha ng mt lng cc chc nng m bn cn.Controller

Page 10

Spring MVC yahoo : ken_uit_9x@yahoo.com


interface ch nh ngha yu cu trch nhim c bn cho mi controller; l x l mt request
v tr v mt model v mt view.
3.3.1 AbstractController and WebContentGenerator
cung cp mt c s h tng, tt c nhng Controller khc nhau ca Spring k tha t
AbstractController, mt lp a ra s h tr caching v, v de, ci t cho mimetype.
Table 13.3. Nhng c tnh c a ra bi AbstractController
Feature

Explanation

Ch cho bit nhng phng thc no controller s chp nhn. Lun


lun n t cho c hai GET v POST, nhng bn c th chnh sa ci
supportedMethods ny mang li phng thc bn mun h tr. Nu mt request c
nhn vi mt method m khng c h tr bi controller, Client s
c thng bo v iu ny (mt ServletException s c nm ra).

requiresSession

Ch ra rng control ny yu cu mt HTTP session lm vic ca n.


Nu mt session khng c biu din khi m mt controller nhn
mt request, ngi dng s c thng tin v iu ny bng mt
ServletException c nm ra.

synchronizeSession

Dng ci ny nu bn mun x l bi controller ng b vi HTTP


session ca ngi dng.

cacheSeconds

Khi bn mun mt controller pht sinh mt ch th caching trong HTTP


response, nh r mt con s r rng y (integer). Mc nh gi tr
ca thuc tnh ny l -1 v th ch th bo rng khng c caching pht
sinh response.

Chnh sa cc controller ca bn c t HTTP 1.0 compatible


useExpiresHeader "Expires" header khi m to response. Mc nh gi tr thuc tnh ny
l true.

useCacheHeader

Chnh sa cc controller ca bn c t HTTP 1.1 compatible


"Cache-Control" header khi m to ra response. Mc nh gi tr ny l
true.

Khi s dng AbstractController nh l lp c s cho controller ca bn, bn ch phi


override phng thc handleRequestInternal(HttpServletRequest, HttpServletResponse),
Page 11

Spring MVC yahoo : ken_uit_9x@yahoo.com


thi hnh theo s logic ca bn, v tr v mt i tng ModelAndView. y l mt v d
ngn gm c mt lp v c khai bo trong web application context.
package samples;
public class SampleController extends AbstractController {
public ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("hello");
mav.addObject("message", "Hello World!");
return mav;
}
}
<bean id="sampleController" class="samples.SampleController">
<property name="cacheSeconds" value="120"/>
</bean>

Lp trn v s khai bo trongweb application context l tt c nhng g bn cn bn cnh


s thit lp mt handler mapping (xem thm Section 13.4, Handler mappings) lm cho
controller rt n gin ny lm vic. Cotrolller ny s pht sinh ch th caching bo vi
client rng cache mi th trong vng 2 pht trc khi xem li. Controller no cng tr v
mt hard-coded view ( n c cn nhc in hnh cho s thc hnh t).
3.3.2 Nhng controller n gin khc
Mc d bn c th m rng AbstractController, Spring cung cp mt s cc implementation
c th, m n a ra chc nng chung chung c s dng trong ng dng MVC n gin.
ParameterizableViewController l c bn, cng nh v d trn, ngoi tr cho s tht l bn
c th c t tn view m n s tr v trong web application context (v nh vy xa i s
cn thit hard-code viewname trong class java).
UrlFilenameViewController kim tra URL v ly tn file ca request v s dng n nh mt
tn view. V d, tn file ca http://www.springframework.org/index.html request l index.
3.3.3 MultiActionController
Spring a ra mt multi-action controller vi n bn tp hp nhiu action vo trong mt
controller, nh vy nhm cc chc nng vi nhau. Multi-action controller trong
org.springframework.web.servlet.mvc.multiaction v l kh nng nh x cc request n
tn phuong thc v gi ng tn phng thc. S dng controller multi-action th c bit
thun tin khi bn c nhiu chc nng ph bin trong mt controller, nhng mun c nhiu
mc (multiple entry) tr vo controller, v d
Table 13.4. Nhng c tnh c a ra bi MultiActionController

Page 12

Spring MVC yahoo : ken_uit_9x@yahoo.com


Feature

delegate

Explanation
C hai kch bn s dng vi MultiActionController. Hoc l bn to
ra mt subclass ca MultiActionController v c t nhng phng
thc s c gii quyt bi MethodNameResolver trn subclass (
trong trng hp ny bn khng cn t delegate), hoc bn nh
ngha mt i tng, trn phng thc ny s resolved by the
MethodNameResolver will be invoked. If you choose this scenario,
you will have to define the delegate using this configuration
parameter as a collaborator.

MultiActionController cn mt chin lc gii quyt phng thc


n c gi, da trn cc request i vo. Chin lc ny c nh
methodNameResolver ngha bi interface MethodNameResolver; MultiActionController
phi by mt thuc tnh sp m bn gi thay th mt resolver m c
th lm cng vic ny.
Nhng phng thc c nh ngha cho mt multi-action controller cn tun theo kiu
sau:
// anyMeaningfulName can be replaced by any methodname
public [ModelAndView | Map | void] anyMeaningfulName(HttpServletRequest,
HttpServletResponse [, Exception | AnyObject]);

Xin ch rng kiu np chng phng thc l khng c cho php (overloading method)
khi n s lm cho MultiActionController nhm ln. Hn na, bn c th nh ngha
exception handlers c kh nng x l cc exception m c nm ra t phng thc m bn
c t.
Tham s Exception c th l mt vi exception, xa hn na n l mt subclass ca
java.lang.Exception or java.lang.RuntimeException. Tham s ca AnyObject c th l mt vi
class. Nhng thm s Request s c bao li bn trong i tng ny cho s s dng thch
hp.
Tm kim mt vi v d hp l v phng thc MultiActionController.
Kiu chun (phng thc interface ca Controller).
public ModelAndView doRequest(HttpServletRequest, HttpServletResponse)

Kiu ny chp nhn mt tham s Login m s c xc nh vi tham s t request.


public ModelAndView doLogin(HttpServletRequest, HttpServletResponse, Login)

Page 13

Spring MVC yahoo : ken_uit_9x@yahoo.com


Kiu phng thc c x l Exception.
public ModelAndView processException(HttpServletRequest, HttpServletResponse,
IllegalArgumentException)

Kiu tr v kiu void (tm hiu thm ti Section 13.11, Convention over configuration ).
public void goHome(HttpServletRequest, HttpServletResponse)

Kiu ny tr v mt kiu Map(tm hiu thm ti Section 13.11, Convention over


configuration ).
public Map doRequest(HttpServletRequest, HttpServletResponse)

MethodNameResolver l phng thc chu trch nhim x l tn da trn request vo. Xem
chi tit bn di v 3 kiu implement ca MethodNameResolver m Spring cung cp m
khng c rng buc.

ParameterMethodNameResolver c kh nng gii quyt mt tham s request v s


dng n nh tn phng thc (http://www.sf.net/index.view?testParam=testIt s
c kt qu trong mt phng thc testIt(HttpServletRequest, HttpServletResponse)
ang c g). Thuc tnh paramName property c t tham s request m c
kim tra).
InternalPathMethodNameResolver ly filename t request path v s dng n nh
l tn phng thc (http://www.sf.net/testing.view s c kt qu trong mt
phng thc testing(HttpServletRequest, HttpServletResponse) ang c gi).
PropertiesMethodNameResolver s dng mt i tng user-defined properties
vi request URLs c nh x n tn phng thc. Khi properties cha ng
/index/welcome.html=doIt v mt request n /index/welcome.html vo, phng
thc doIt(HttpServletRequest, HttpServletResponse) c gi. Tn phng thc
ny ca resolver lm vic vi PathMatcher, v th nu properties cha
/**/welcom?.html, N cng s lm vic!

y l mt v d. Trc tin, mt v d hin th ParameterMethodNameResolver v


delegate property, n s chp nhn nhng request n URLs vi tham s phng thc
c lng vo v t ly Index:
<bean id="paramResolver" class="org....mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="method"/>
</bean>
<bean id="paramMultiController" class="org....mvc.multiaction.MultiActionController">
<property name="methodNameResolver" ref="paramResolver"/>
<property name="delegate" ref="sampleDelegate"/>
</bean>

Page 14

Spring MVC yahoo : ken_uit_9x@yahoo.com


<bean id="sampleDelegate" class="samples.SampleDelegate"/>

## together with
public class SampleDelegate {
public ModelAndView retrieveIndex(HttpServletRequest req, HttpServletResponse
resp) {
return new ModelAndView("index", "date", new
Long(System.currentTimeMillis()));
}
}

Khi s dng delegate c biu din trn, chng ta c th s dng


PropertiesMethodNameResolver kim mt s xng hp ca URLs vi phng thc m
chng ta nh ngha:
<bean id="propsResolver" class="org....mvc.multiaction.PropertiesMethodNameResolver">
<property name="mappings">
<value>
/index/welcome.html=retrieveIndex
/**/notwelcome.html=retrieveIndex
/*/user?.html=retrieveIndex
</value>
</property>
</bean>
<bean id="paramMultiController" class="org....mvc.multiaction.MultiActionController">
<property name="methodNameResolver" ref="propsResolver"/>
<property name="delegate" ref="sampleDelegate"/>
</bean>

3.3.4 Lnh ca cc controller ( command controller )


Spring's command controllers l mt phn c s ca gi Spring Web MVC. Command
controllers cung cp mt li tng tc vi d liu ca cc i tng v lin kt ng cc
tham s (parameter) t HttpServletRequest n d liu ca i tng c c t. Chng
thi hnh hi ging role ca Struts ActionForm, nhng trong Spring, d liu i tng ca
bn khng phi thc thi mt interface ca framework c t. Trc tin, chng ta xem xt
command controller no l sn sng c dng mt cch d dng nht m khng cn cu
hinh ci t.
AbstractCommandController - mt command controller, bn c th s dng to ra
command controller ca ring bn, c kh nng lin kt cc tham s request vo i tng
d liu bn c t. Class ny khng a ra hnh dng ca chc nng; n lm bng cch no
Page 15

Spring MVC yahoo : ken_uit_9x@yahoo.com


a ra tnh nng kim chng (validation) v bn c t trong controller ca chnh n
nhng g lm vi i tng command m c xc nh vi gi tr tham s ca request.

AbstractFormController mt controller tru tng a ra s h tr form


submission. S dng controller ny bn c th m hnh cc form v xc n chng
ang s dng mt i tng Command bn ly t controller. Sau khi mt user in
y form, AbstractFormController lin kt cc trng (field), Kim chng (validate)
i tng command, v iu khiu cc i tng tr li controller ly action
thch hp. Cc c tnh c h tr l: invalid form submission (resubmission),
validation, v normal form workflow. Bn thc thi phng tc xc nh view no
l c s dng cho form presentation v thnh cng. S dng controller nu bn
cn cc form, nhng khng mun c t view gi hin th user trong application
context.
SimpleFormController mt form controller cung cp s h tr thm ch nhiu hn
khi to mt form vi mt i tng corresponding command.
SimpleFormController cho bn c t mt command object, mt viewname cho
form, mt viewname cho trang bn mun hin th user khi form submission
thnh cng, v thm na.
AbstractWizardFormController nh tn class c ngh, y l mt abstract
class - wizard controller ca bn nn k tha n. iu ny c ngha l bn phi thc
thi phng thc validatePage(), processFinish() v processCancel().

Bn hu nh chc chn rng mun vit mt contractor, n s l ci ti thiu nht gi


setPages() v setCommandName(). Former ly tham s nh l mt mng kiu String. Mng
ny l danh sch cc view m n bao gm wizard ca bn. Sau cng ly tham s ca n nh
mt kiu chui, N s c s dng ch dn i tng command t trong cc view ca
bn.
Nh vi mt vi th hin ca AbstractFormController, bn s c yu cu s dng mt i
tng command mt JavaBean m n s c nh v vi d liu t nhng form ca bn.
Bn c th lm ci ny theo mt trong hai cch sau: hoc l gi setCommandClass() t
constructor vi class ca i tng command, hoc thc thi phng thc
formBackingObject().
AbstractWizardFormController c mt s phng thc c th m bn c th override.
Trong s ny, ci m thch tm kim v rt hu dng l: referenceData(..) bn c th s dng
thng qua model data n view trong form ca mt Map; getTargetPage() nu wizard
ca bn cn thay i th t trang hoc b st cc trang ng; v onBindAndValidate() nu
bn mun override built-in binding v validation workflow.

Page 16

Spring MVC yahoo : ken_uit_9x@yahoo.com


Cui cng, n ng gi tr ra ngoi setAllowDirtyBack() v setAllowDirtyForward(), m
bn c th gi t getTargetPage() cho php nhng ngi dng backwards v forwards
trong wizard thm ch nu nu kim chng c xc nhn l khng t (validation fail) cho
trang hin ti.
For a full list of methods, see the Javadoc for AbstractWizardFormController. There is an
implemented example of this wizard in the jPetStore included in the Spring distribution:
org.springframework.samples.jpetstore.web.spring.OrderFormController.

3.4 Handler mappings


S dng mt handler mapping chng ta c th nh x mt web request n mt handler
thch hp. C mt vi handler mapping chng ta c th s dng mt cch t nhin, v d:
SimpleUrlHandlerMapping hoc BeanNameUrlHandlerMapping.
Chc nng ca mt HandlerMapping c bn cung cp l s phn phi ca mt
HandlerExecutionChain, N cn cha handler ph hp vi request, v cng c th cha
ng mt danh sch cc handler chn m c p dng cho request. Khi mt request vo,
DispatcherServlet s iu khin n thng qua handler mapping phn tch v kim tra
request v mang ln vi mt HandlerExecutionChain thch hp. Sau DispatcherServlet
s thc thi handler v cc b chn trong chui thc thi (nu c).
Khi nim configurable handler mappings l c th ty cha ng cc b chn (thc thi
trc khi v sau khi handler thc s c thc thi, hoc c hai) l thc s mnh m. Khi
lng cc chc nng c h tr c th c xy dng trong vic xy dng cc
HandlerMapping ty . Cch x l ca mt handler mapping ty l mt handler khng ch
da trn URL ca request m n cng m t trng thi ca session lin kt vi request.
Phn ny m t hai handler mapping thng dng. Chng m rng t
AbstractHandlerMapping v cng c nhng thuc tnh sau:

interceptors: danh sch cc b chn dng. Xem thm Section 13.4.3, Intercepting
requests - the HandlerInterceptor interface.
defaultHandler: default handler dng, Khi handler mapping ny khng hp vi
handler no.
order: da trn gi tr ca thuc tnh order (xem org.springframework.core.Ordered
interface), Spring s sp xp tt c cc handler mappings ang c trong context v p
dng handler u tin.

Page 17

Spring MVC yahoo : ken_uit_9x@yahoo.com

alwaysUseFullPath: nu thuc tnh ny c set l true, Spring s s dng ng


dn y servlet context hin ti tm handler thch hp. Nu thuc tnh ny
c set l false (mc nh), ng dn bn trong servlet mapping hin ti s c
s dng . V d, Nu mt servlet c nh x s dng /testing/* v
alwaysUseFullPath c set l true, /testing/viewPage.html s c s dng, Tri
li nu thuc tnh c set l false, /viewPage.html s c s dng.
urlPathHelper: s dng thuc tnh ny, bn c th s dng UrlPathHelper khi kim
tra URLs. Bnh thng, Bn khoong nn thay i gi tr mc nh.
urlDecode: Gi tr mc nh ca thuc tnh ny l false. HttpServletRequest tr v
request URLs v URIs m khng c decoded. Nu bn khng mun chng c
m ha trc khi HandlerMapping s dng chng tm mt handler thch hp ,
bn phi t thuc tnh ny l true (n yu cu JDK 1.4). Phng thc decode s
dng hoc l encoding c c t bi request hoc default ISO-8859-1 encoding .
lazyInitHandlers: allows for lazy initialization of singleton handlers (prototype
handlers are always lazily initialized). Default value is false.

3.5 Views.
3.5.1 Chaining ViewResolvers
Spring h tr nhiu view resolver, v chng c sp xp mt cch th t theo mt chui
mc xch. Trong v d bn di, chui mc xch ca chng ta c hai view (
InternalResourceViewResolver):
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="excelViewResolver"
class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
<!-- in views.xml -->
<beans>
<bean name="report" class="org.springframework.example.ReportExcelView"/>
</beans>

Page 18

Spring MVC yahoo : ken_uit_9x@yahoo.com


Nu mt view resolver c th khng tm thy view no thch hp, Spring s phn tch trong
context xem c view resolver no c cu hnh khng. Nu c, n s tip tc phn tch
yu cu, tri li n s tr v mt ngoi l.
Khi vit mt view resolver, chng ta cn phi xc tnh n cc ngoi l m view resolver tr
v
3.5.2 Redirecting to views
Vi JSP, n c x l thng qua Servlet/JSP engine, iu ny c x l n gin thng qua
InternalResourceViewResolver / InternalResourceView, n s dng mt trong cc phng
thc sau RequestDispatcher.forward(..) hoc RequestDispatcher.include().
3.5.2.1 RedirectView
s dng c ch redirect, Spring cung cp RedirectView . N nhn kt qu ca phng
thc HttpServletResponse.sendRedirect() x l
The RedirectView simply ends up issuing an HttpServletResponse.sendRedirect() call,
which will come back to the client browser as an HTTP redirect. All model attributes are
simply exposed as HTTP query parameters. This does mean that the model must contain
only objects (generally Strings or convertible to Strings) which can be readily converted to
a string-form HTTP query parameter.
3.5.2.2 The redirect: prefix
Nu controller to RedirectView trn chnh n, th s controller s khng nhn bit c l
c redirect. Controller ch gii quyt trn tn ca view c chn vo.
Redirect c th: prefix cho php iu ny t c. Nu tn view c tr v c tin t l
redirect, khi UrlBasedViewResolver (v tt c cc lp con) s nhn ra y l l mt
redirect. View s c thit i nh l mt redirect URL.
3.5.2.3 The forward: prefix
Forward: prefix c x l bi UrlBasedViewResolver v subclasses. Tt c nhng g n lm
l to mt InternalResourceView (bng cch gi RequestDispatcher.forward()) . v vy
khng phi s dng prefix ny khi s dng InternalResourceViewResolver /
InternalResourceView.
Nh redirect prefix, controller s khng phi nhn bit rng c mt redirect nu chn
tn view vo controller

3.6 S dng locales


Cc phn ca Spring u h tr internationalization. DispatcherServlet cho php bn x l
cc message t ng bng cch s dng v tr ca client. N c lm bi LocaleResolver
objects.
Page 19

Spring MVC yahoo : ken_uit_9x@yahoo.com


Khi request n, DispatcherServlet tm kim mt locale resolver v nu n tm thy n c
gng s dng locale resolver ny t locale. S dng phng thc
RequestContext.getLocale().
Bn cch vic gii quyt cc locale t ng bn cng c th nh km mt b chn n
handler mapping thay i locale theo mt tnh hung c bit
Locale resolvers v interceptors c nh ngha trong gi
org.springframework.web.servlet.i18n, v c cu hnh trong application context theo
cch n gin
3.6.1 AcceptHeaderLocaleResolver
Locale resolver phn tch accept-language header trong request.
3.6.2 CookieLocaleResolver
Locale resolver phn tch mt Cookie. Nu cookie c s dng n s dng local m cookie
c t
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="clientlanguage"/>
<!-- in seconds. If set to -1, the cookie is not persisted (deleted when browser
shuts down) -->
<property name="cookieMaxAge" value="100000">
</bean>

Table 13.6. CookieLocaleResolver properties


Property
cookieName

Default
classname +
LOCALE

Description
Tn ca cookie

Thi gian ti a m cookie c hiu lc trn client. Nu l


cookieMaxAge Integer.MAX_INT -1 th cookie s khng c lu li lu. N ch c hiu lc
cho ti khi ngi dng tt browser.

cookiePath

S dng tham s ny chng ta c th gii hn tnh cht


ring t ca cookie. Khi cookiePath c t t, Cookie
ch c th hin trong c trng thy ng dn
ny.

Page 20

Spring MVC yahoo : ken_uit_9x@yahoo.com

3.6.3 SessionLocaleResolver
SessionLocaleResolver cho php bn ly cc locale t session.
3.6.4 LocaleChangeInterceptor
Bn c th xy dng s thay i ca locale bng cch s dng LocaleChangeInterceptor. B
chn ny cn c thm vo handler mappings, trong request v thay i locale (n gi
setLocale() ca LocaleResolver, m n cng tn ti trong ng cnh ny).
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="siteLanguage"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
</list>
</property>
<property name="mappings">
<value>/**/*.view=someController</value>
</property>
</bean>

Tt gi n tt c *.view cha mt tham s c tn l siteLanguage.V d:


http://www.sf.net/home.view?siteLanguage=nl s thay i ngn ng ca site thnh Dutch.

3.7 S dng themes


3.7.1 Gii thiu
Theme c Spring web MVC framework cung cp, cho php bn nng cp kinh nghim
ca ngi dng bng vic lm cho ng dng ca bn look and feel bi theme. Theme c bn
l mt tp hp cc ti nguyn tnh nh l hnh, style sheet.
3.7.2 nh ngha themes
Cu hnh org.springframework.ui.context.ThemeSource. WebApplicationContext interface
k tha ThemeSource nhng y nhim n chu trch nhim thc thi. Mc nh s y nhim
ny s l org.springframework.ui.context.support.ResourceBundleThemeSource, lp ny
ly cc file properties t classpath gc. Nu mun to mt ThemeSource implementation
hoc cn cu hnh basename prefix ca ResourceBundleThemeSource, bn c th ng k
Page 21

Spring MVC yahoo : ken_uit_9x@yahoo.com


mt bean trong application context vi tn l "themeSource". Web application context s t
ng nhn bit bean v khi ng n.
V d:
styleSheet=/themes/cool/style.css
background=/themes/cool/img/coolBg.jpg
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link rel="stylesheet" href="<spring:theme code="styleSheet"/>"
type="text/css"/>
</head>
<body background="<spring:theme code="background"/>">
...
</body>
</html>

Mc nh ResourceBundleThemeSource s dng mt basename prefix rng. Cc file


properties s c ti t gc ca classpath, v th chng ta phi nhp vo cool.properties
theme ca chng ta c nh ngha trong mt th mc ti gc ca classpath, e.g. trong
/WEB-INF/classes. Ch rng ResourceBundleThemeSource s dng c ch ti ca chun
Java resource bundle, cho php internationalization trn ton b cc theme.
3.7.3 Theme resolvers
Chng ta c theme v by gi vic cn li l chng ta s quyt nh s dng theme no.
The DispatcherServlet s tm kim tn bean "themeResolver" xc nh ThemeResolver.
ThemeResolver lm vic tng t nh l LocaleResolver. N c th d ra theme no s
c s dng cho request c th v c th chnh sa theme ca request. Nhng theme
resolver sau c cung cp bi Spring:
Table 13.7. ThemeResolver implementations
Class

Description

FixedThemeResolver

S dng mt theme c nh, chn thuc tnh "defaultThemeName.

SessionThemeResolver

Theme c duy tr trong HTTP session. N ch cn c t trong


mi session, nhng khng bn vng gia cc session.

CookieThemeResolver Theme c chn c cha trong cookie trn my user.


Spring cng cung cp ThemeChangeInterceptor, n cho php thay i thm trn mi
request bng cch chn vo mt tham s request c bn.
Page 22

Spring MVC yahoo : ken_uit_9x@yahoo.com


3.8 Multipart support ca Spring (fileupload)
3.8.1 Introduction
Spring xy dng multipart support x l fileupload trong ng dng web.
MultipartResolver c nh ngha trong gi org.springframework.web.multipart. Spring
cung cp MultipartResolvers cho vic s dng cng vi Commons FileUpload
(http://jakarta.apache.org/commons/fileupload) v COS FileUpload
(http://www.servlets.com/cos). Lm th no uppload files s c m t ngay bn di
3.8.2 Using the MultipartResolver
V d vi CommonsMultipartResolver:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
This is an example using the CosMultipartResolver:
<bean id="multipartResolver"
class="org.springframework.web.multipart.cos.CosMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>

Trong trng hp CommonsMultipartResolver, bn cn s dng commons-fileupload.jar;


trong trng hp ca CosMultipartResolver, s dng cos.jar.
3.8.3 Handling a file upload in a form
Sau khi MultipartResolver hon thnh cng vic ca n, request s c x l nh nhng
request khc.
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="upload.form" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>

enctype="multipart/form-data l cn thit browser bit cch m cc trng ca


multipart.

Page 23

Spring MVC yahoo : ken_uit_9x@yahoo.com


Nhng thuc tnh khc s khng t ng chuyn qua string hoc kiu d liu c bn
(primitive type), c th t d liu binary vo trong cc i tng ca bn object bn
phi ng k mt Custom editor vi ServletRequestDatabinder. Chng ta c hai editor cho
vic x l file l StringMultipartEditor (c th chuyn cc file thnh String) v
ByteArrayMultipartEditor (chuyn cc file thnh dy cc byte).
So, to be able to upload files using a (HTML) form, declare the resolver, a url mapping to a
controller that will process the bean, and the controller itself.
<beans>
<!-- lets use the Commons-based implementation of the MultipartResolver
interface -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/upload.form=fileUploadController
</value>
</property>
</bean>
<bean id="fileUploadController" class="examples.FileUploadController">
<property name="commandClass" value="examples.FileUploadBean"/>
<property name="formView" value="fileuploadform"/>
<property name="successView" value="confirmation"/>
</bean>
</beans>

After that, create the controller and the actual class to hold the file property.
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
let's see if there's content there
byte[] file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything
}

Page 24

Spring MVC yahoo : ken_uit_9x@yahoo.com


// well, let's do nothing with the bean for now and return
return super.onSubmit(request, response, command, errors);
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder
binder)
throws ServletException {
// to actually be able to convert Multipart instance to byte[]
// we have to register a custom editor
binder.registerCustomEditor(byte[].class, new
ByteArrayMultipartFileEditor());
// now Spring knows how to handle multipart object and convert them
}
}
public class FileUploadBean {
private byte[] file;
public void setFile(byte[] file) {
this.file = file;
}
public byte[] getFile() {
return file;
}
}

FileUploadBean c mt kiu ca thuc tnh l byte[], n nm gi file. Controller ng k mt


custom editor Spring bit lm th no chuyn i cc i tng multipart, resolver
tm thy cc thuc tnh c c t bi bean. Trong v d ny, khng c g c lm vi
thuc tnh byte[] ca bean, nhng trong bi thc hnh ny bn c th lm bt c ci g bn
mun (lu n vo c s d liu, gi n bng mail n ai , v.v).
Mt v d tng ng, mt file c gii hn vi thuc tnh String-typed trn mt (form
backing) i tng:
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
let's see if there's content there
String file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything

Page 25

Spring MVC yahoo : ken_uit_9x@yahoo.com


}
// well, let's do nothing with the bean for now and return
return super.onSubmit(request, response, command, errors);
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder
binder)
throws ServletException {
// to actually be able to convert Multipart instance to a String
// we have to register a custom editor
binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
// now Spring knows how to handle multipart object and convert them
}
}
public class FileUploadBean {
private String file;
public void setFile(String file) {
this.file = file;
}
public String getFile() {
return file;
}
}

V d cui l upload mt file text, trong trng hp ny khng cn ng k mt custom


editor
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
let's see if there's content there
MultipartFile file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything
}
// well, let's do nothing with the bean for now and return
return super.onSubmit(request, response, command, errors);
}

Page 26

Spring MVC yahoo : ken_uit_9x@yahoo.com


}
public class FileUploadBean {
private MultipartFile file;
public void setFile(MultipartFile file) {
this.file = file;
}
public MultipartFile getFile() {
return file;
}
}

3.9 Using Spring's form tag library


Spring cung cp mt b cc tag ton din cho vic x l form khi s dng JSP v Spring Web
MVC. Mi tag cung cp s h tr cho mt b cc thuc tnh tng ng trong HTML tag ,
lm cho cc tags thn thin v trc quan hn. Tag-generated HTML l HTML 4.01/XHTML
1.0 compliant.
Khng ging nh cc th vin form/input tag khc, th vin Spring form tag c tch hp
vi Spring Web MVC, Cho cc tag truy cp n cc i tng command v nhng d liu
lin quan m controller ca bn cn. V d, form tags lm cho cc JSP d dng pht trin,
c v bo tr.
Chng ta included cc generated HTML ni m cc tag yu cu c ch gii.
3.9.1 Configuration
Th vin form tag c ng gi trong spring.jar. Library descriptor c gi l springform.tld.
s dng th vin cc tag phi thm s ch dn u trang JSP ca bn:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

3.9.2 Form tag


<form:form>
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
</tr>
<tr>

Page 27

Spring MVC yahoo : ken_uit_9x@yahoo.com


<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>

Gi tr firstName v lastName c ly t i tng command PageContext ca page


controller.
Form HTML chun:
<form method="POST">
<table>
<tr>
<td>First Name:</td>
<td><input name="firstName" type="text" value="Harry"/></td>
<td></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastName" type="text" value="Potter"/></td>
<td></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form>
<form:form commandName="user">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>

Page 28

Spring MVC yahoo : ken_uit_9x@yahoo.com


3.9.3 Input tag
3.9.4 Checkbox tag
public class Preferences {
private boolean receiveNewsletter;
private String[] interests;
private String favouriteWord;
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getInterests() {
return interests;
}
public void setInterests(String[] interests) {
this.interests = interests;
}
public String getFavouriteWord() {
return favouriteWord;
}
public void setFavouriteWord(String favouriteWord) {
this.favouriteWord = favouriteWord;
}
}

<form:form>
<table>
<tr>
<td>Subscribe to newsletter?:</td>
<%-- Approach 1: Property is of type java.lang.Boolean --%>
<td><form:checkbox path="preferences.receiveNewsletter"/></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Interests:</td>
<td>
<%-- Approach 2: Property is of an array or of type
java.util.Collection --%>

Page 29

Spring MVC yahoo : ken_uit_9x@yahoo.com


Quidditch: <form:checkbox path="preferences.interests"
value="Quidditch"/>
Herbology: <form:checkbox path="preferences.interests"
value="Herbology"/>
Defence Against the Dark Arts: <form:checkbox
path="preferences.interests"
value="Defence Against the Dark Arts"/>
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Favourite Word:</td>
<td>
<%-- Approach 3: Property is of type java.lang.Object --%>
Magic: <form:checkbox path="preferences.favouriteWord"
value="Magic"/>
</td>
<td>&nbsp;</td>
</tr>
</table>
</form:form>

<tr>
<td>Interests:</td>
<td>
Quidditch: <input name="preferences.interests" type="checkbox"
value="Quidditch"/>
<input type="hidden" value="1" name="_preferences.interests"/>
Herbology: <input name="preferences.interests" type="checkbox"
value="Herbology"/>
<input type="hidden" value="1" name="_preferences.interests"/>
Defence Against the Dark Arts: <input name="preferences.interests"
type="checkbox"
value="Defence Against the Dark Arts"/>
<input type="hidden" value="1" name="_preferences.interests"/>
</td>
<td>&nbsp;</td>
</tr>

3.9.5 Radiobutton tag


<tr>
<td>Sex:</td>
<td>Male: <form:radiobutton path="sex" value="M"/> <br/>
Female: <form:radiobutton path="sex" value="F"/> </td>
<td>&nbsp;</td>
</tr>

3.9.6 Password tag


<tr>
<td>Password:</td>

Page 30

Spring MVC yahoo : ken_uit_9x@yahoo.com


<td>
<form:password path="password" />
</td>
</tr>

<tr>
<td>Password:</td>
<td>
<form:password path="password" value="^76525bvHGq" showPassword="true" />
</td>
</tr>

3.9.7 Select tag


<tr>
<td>Skills:</td>
<td><form:select path="skills" items="${skills}"/></td>
<td></td>
</tr>

<tr>
<td>Skills:</td>
<td><select name="skills" multiple="true">
<option value="Potions">Potions</option>
<option value="Herbology" selected="true">Herbology</option>
<option value="Quidditch">Quidditch</option></select></td>
<td></td>
</tr>

3.9.8 Option tag


<tr>
<td>House:</td>
<td>
<form:select path="house">
<form:option value="Gryffindor"/>
<form:option value="Hufflepuff"/>
<form:option value="Ravenclaw"/>
<form:option value="Slytherin"/>
</form:select>
</td>
</tr>
<tr>
<td>House:</td>
<td>
<select name="house">
<option value="Gryffindor" selected="true">Gryffindor</option>
<option value="Hufflepuff">Hufflepuff</option>
<option value="Ravenclaw">Ravenclaw</option>
<option value="Slytherin">Slytherin</option>
</select>

Page 31

Spring MVC yahoo : ken_uit_9x@yahoo.com


</td>
</tr>

3.9.9 Options tag


<tr>
<td>Country:</td>
<td>
<form:select path="country">
<form:option value="-" label="--Please Select"/>
<form:options items="${countryList}" itemValue="code" itemLabel="name"/>
</form:select>
</td>
<td></td>
</tr>

If the User lived in the UK, the HTML source of the 'Country' row would look like:
<tr>
<td>Country:</td>
<tr>
<td>Country:</td>
<td>
<select name="country">
<option value="-">--Please Select</option>
<option value="AT">Austria</option>
<option value="UK" selected="true">United Kingdom</option>
<option value="US">United States</option>
</select>
</td>
<td></td>
</tr>
<td></td>
</tr>

As the example shows, the combined usage of an option tag with the options tag generates
the same standard HTML, but allows you to explicitly specify a value in the JSP that is for
display only (where it belongs) such as the default string in the example: "-- Please Select".
3.9.10 The textarea tag
This tag renders an HTML 'textarea'.
<tr>
<td>Notes:</td>
<td><form:textarea path="notes" rows="3" cols="20" /></td>
<td><form:errors path="notes" /></td>
</tr>

Page 32

Spring MVC yahoo : ken_uit_9x@yahoo.com


3.9.11 The hidden tag
<form:hidden path="house" />
<input name="house" type="hidden" value="Gryffindor"/>

3.9.12 Errors tag


public class UserValidator implements Validator {
public boolean supports(Class candidate) {
return User.class.isAssignableFrom(candidate);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required",
"Field is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required",
"Field is required.");
}
}

The form.jsp would look like:


<form:form>
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
<%-- Show errors for firstName field --%>
<td><form:errors path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
<%-- Show errors for lastName field --%>
<td><form:errors path="lastName" /></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>

If we submit a form with empty values in the firstHame and lastName fields, this is what
the HTML would look like:
<form method="POST">
<table>
<tr>

Page 33

Spring MVC yahoo : ken_uit_9x@yahoo.com


<td>First Name:</td>
<td><input name="firstName" type="text" value=""/></td>
<%-- Associated errors to firstName field displayed --%>
<td><span name="firstName.errors">Field is required.</span></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastName" type="text" value=""/></td>
<%-- Associated errors to lastName field displayed --%>
<td><span name="lastName.errors">Field is required.</span></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form>

What if we want to display the entire list of errors for a given page? The example below
shows that the errors tag also supports some basic wildcarding functionality.

path="*" - displays all errors


path="lastName*" - displays all errors associated with the lastName field

The example below will display a list of errors at the top of the page, followed by fieldspecific errors next to the fields:
<form:form>
<form:errors path="*" cssClass="errorBox" />
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" /></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>

Page 34

Spring MVC yahoo : ken_uit_9x@yahoo.com


The HTML would look like:
<form method="POST">
<span name="*.errors" class="errorBox">Field is required.<br/>Field is
required.</span>
<table>
<tr>
<td>First Name:</td>
<td><input name="firstName" type="text" value=""/></td>
<td><span name="firstName.errors">Field is required.</span></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input name="lastName" type="text" value=""/></td>
<td><span name="lastName.errors">Field is required.</span></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Save Changes" />
</td>
</tr>
</form>

Page 35

You might also like