Professional Documents
Culture Documents
Spring MVC Full Version Vienamese
Spring MVC Full Version Vienamese
1 2 3 Gii thiu ........................................................................................................................................................ 1 Pluggability of other MVC implementations ..................................................................................... 2 Features of Spring Web MVC .................................................................................................................. 2 3.1 3.2 3.3 Spring WebFlow ................................................................................................................................... 2 DispatcherServlet ................................................................................................................................ 4 Controllers........................................................................................................................................... 10 AbstractController and WebContentGenerator ........................................................... 11 Nhng controller n gin khc ........................................................................................ 12 MultiActionController ............................................................................................................ 12 Lnh ca cc controller ( command controller ) ......................................................... 15
Handler mappings ............................................................................................................................ 17 Views. .................................................................................................................................................... 18 Chaining ViewResolvers ........................................................................................................ 18 Redirecting to views ............................................................................................................... 19 AcceptHeaderLocaleResolver ............................................................................................. 20 CookieLocaleResolver ............................................................................................................ 20 SessionLocaleResolver........................................................................................................... 21 LocaleChangeInterceptor ..................................................................................................... 21 Gii thiu ..................................................................................................................................... 21 nh ngha themes ................................................................................................................... 21 Theme resolvers ....................................................................................................................... 22 Introduction ............................................................................................................................... 23 Using the MultipartResolver ............................................................................................... 23 Handling a file upload in a form ......................................................................................... 23 Configuration ............................................................................................................................. 27 Form tag ...................................................................................................................................... 27
3.5.1 3.5.2 3.6 3.6.1 3.6.2 3.6.3 3.6.4 3.7 3.7.1 3.7.2 3.7.3 3.8 3.8.1 3.8.2 3.8.3 3.9 3.9.1 3.9.2
3.9.3 3.9.4 3.9.5 3.9.6 3.9.7 3.9.8 3.9.9 3.9.10 3.9.11 3.9.12
Input tag ...................................................................................................................................... 29 Checkbox tag .............................................................................................................................. 29 Radiobutton tag ........................................................................................................................ 30 Password tag ............................................................................................................................. 30 Select tag ..................................................................................................................................... 31 Option tag.................................................................................................................................... 31 Options tag ................................................................................................................................. 32 The textarea tag ................................................................................................................... 32 The hidden tag ...................................................................................................................... 33 Errors tag ................................................................................................................................ 33
Page 3
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
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
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
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 Controllers Handler mappings Explanation Controllers l cc thnh phn c to thnh t phn 'C' ca MVC. 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
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 multipart file resolver Handler exception resolver(s) 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 Mt multipart file resolver a ra cc chc nng x l file upload t HTML form 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
Parameter
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.
contextClass
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
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
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). 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. Dng ci ny nu bn mun x l bi controller ng b vi HTTP session ca ngi dng. 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.
requiresSession
synchronizeSession
cacheSeconds
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. 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.
useCacheHeader
Khi s dng AbstractController nh l lp c s cho controller ca bn, bn ch phi override phng thc handleRequestInternal(HttpServletRequest, HttpServletResponse), Page 11
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
delegate
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)
Page 13
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
## 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
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
Page 17
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
Table 13.6. CookieLocaleResolver properties Property cookieName Default classname + LOCALE Tn ca cookie Description
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. 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.
cookiePath
Page 20
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.
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 FixedThemeResolver SessionThemeResolver Description S dng mt theme c nh, chn thuc tnh "defaultThemeName. 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
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>
Page 23
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
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
Page 26
Page 27
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
<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> </td> </tr> <tr> <td>Interests:</td> <td> <%-- Approach 2: Property is of an array or of type java.util.Collection --%>
Page 29
<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> </td> </tr>
Page 30
<tr> <td>Password:</td> <td> <form:password path="password" value="^76525bvHGq" showPassword="true" /> </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>
Page 31
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
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
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
Page 35