版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
提Spring版本附带了PetClinic示例,它是一个在简单的表单处理的上下文中,利用了本节中说明的注解支持的Web应用程序。可以在“samples/petclinic” 中找到PetClinic应用程序。另外一个建立在基于注解的WebMVC上的示例应用程序,请见imagedb。这个示例集中在无状态的multi-action控制器,包括多段文件上传的处理。可以在“samples/imagedb” 找到imagedb应用程序。1.建立dispatcher只有对应的HandlerMap(为了实现类型级别的注解)和/或HandlerAdapter(为了实现方法DispatcherPortlet中都是缺省的行为。的DefaultAnnotationHandlerMap和/或AnnotationMethodHandlerAdapter同样被定义——假设想要使用@RequestMap。<?xmlversion="1.0"encoding="UTF- xmlns="<bean<bean>...(controllerbeandefinitions)1:雁联zfpt-配置 和/或 ponent-scanbase-<bean ><property<property<ref<ref<bean><property<bean<beanid="sessionInterceptor"<beanid="superUserInterceptor"<?xml <?xml y-name>Spring <description>SpringPetClinicsample"hKeyofthesystempropertythatshouldspecifytherootdirectoryofthiswebapp.AppliedbyWebAppRootListenerorLog4jConfigListener.LocationoftheLog4Jconfigfile,forinitializationandrefreshchecks.AppliedbyLog4jConfigListener.LocationoftheXMLfilethatdefinestherootapplicationAppliedbyCanbeset"/WEB-INF/applicationContext-hibernate.xml"fortheHibernate"/WEB-INF/applicationContext-jpa.xml"fortheJPAone,"/WEB-INF/applicationContext-jdbc.xml"fortheJDBCTousetheJPAvariantabove,youwillneedtoenableSpringload-timeweavinginyourserverenvironment.Outofthebox,Springwilltrytodetecttherunningenvironmentandusetheappropriateweaverbutiffails,onemustenableonebyhandorusetheVM-wideSeePetClinic'sreadmeand/orSpring'sJPA ationformore ConfiguresLog4JforthiswebAsthiscontextspecifiesacontext-param"log4jConfigLocation",itsisusedtoloadtheLog4Jconfiguration,includingperiodicrefreshWouldfallbacktodefaultLog4Jinitialization(non-refreshing)ifnocontext-paramsareExportsa"webapprootkey",i.e.asystempropertythatspecifiesdirectoryofthiswebapp,forusageinlogfileThiswebappspecifies"petclinic.root"(perties<!--Leavethelistenercommented-outifusingJBoss--Loadstherootapplicationcontextofthiswebappatbydefaultfrom"/WEB-NotethatyouneedtofallbacktoSpring'sContextLoaderServletJ2EEserversthatdonotfollowtheServlet2.4initializationUsetoaccessitanywhereinthewebapplication,outsideoftheTherootcontextistheparentofallservlet-specificThismeansthatitsbeansareautomaticallyavailableinthesechildbothforgetBean(name)callsand(external)beanServletthatdispatchesrequesttoregisteredhandlers(ControllerHasitsownapplicationcontext,bydefaultdefinedin"{servlet-name}-i.e."petclinic-AwebappcancontainanynumberofsuchNotethatthiswebapphasasharedrootapplicationcontext,servingasofallDispatcherServletMapsthepetclinicdispatcherto"*.do".Allhandlermapspetclinic-servlet.xmlwillbydefaultbeappliedtothisIfa isn'ta/*subpath,thehandler sarerelativetothewebappNOTE:Asingledispatchercanbemappedtomultiplepaths,likeany <!--Disysastacktrace--3:雁联如果你想要自定义映射策略,显式的定义一个DefaultAnnotationHandlerMap和/或AnnotationMethodHandlerAdapter也有实际意义。例如,指定一个自定义的PathMatcher或者一个简单的基于注解的SpringMVCControllerorg.springframework.web.servlet.mvc.Controller接SimpleFormControllerMultiActionControllerController的。在定义Controller后,一个重要的是在SpringMVC的配置文件中通过HandlerMap定义请求和Controller实现效果启动Tomcat,发送URL请求,BbtForumController1.BbtForumController.javapackageimportimportorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importimportorg.springframework.web.bind.annotation.RequestMap;importorg.springframework.web.bind.annotation.RequestMethod;import publicclassBbtForumController{privateBbtForumService@RequestMap//<——publicStringlistAllBoard(){System.out.println("calllistAllBoardmethod.");return"listBoard";}}在①处使用了两个注解分别是@Controller和@RequestMap“使用Spring2.5基于注解驱动的IoC”这篇文章里笔者曾经过@Controller@Service以及@Repository和@Component注解的作用是等价的:将一个类成为Spring容器的Bean。由于SpringMVC的Controller必须事先是一个Bean,所以@Controller真正让BbtForumController具备SpringMVCController功能的是@RequestMap这个注解。@RequestMapController和特定请求关联起来;还可以标注在方法签名处,以BbtForumController关联“/forum.do体地指定listAllBoard()方法来处理请求。所以在类处标注的@RequestMap相当于让POJO实现了Controller接口,而在方法定义处的@RequestMap相当于让POJO扩展Spring预定义的Controller(如SimpleFormController等。2.web.xml:启用Spring容器和SpringMVC框架SpringMVCSpringMVCxxx-servlet.xml配置文件中做一些手脚。在此之前,还是先来看一下web.xml的配置吧<?xmlversion="1.0"encoding="UTF-<web-appxmlns="h /xml/ns/javaee/web-app_2_5.xsd"<disy-name>SpringAnnotationMVC y-<!--Spring<!--Spring容器启动器--<!--SpringMVCServletWEB-INF/annomvc-servlet.xmlSpringMVC模块-->3.annomvc-servlet.xmlweb.xml中定义了一个名为annomvc的SpringMVC模块,按照SpringMVC的契约,需要在WEB-INF/annomvc-servlet.xmlSpringMVCannomvc-servlet.xml的配置内容如下所<?xmlversion="1.0"encoding="UTF-xmlns="xsi:schemaLocation="webBean ponent-scanbase-SpringMVCPOJO的映射<bean<!--p:prefix="/WEB-INF/jsp/"p:suffix=".jsp"/>因为Spring所有功能都在Bean的基础上演化而来,所以必须事先将ControllerBean,这是通过在类中标注@Controller并在annomvc-servlet.xml中启用组件扫描机制来完成的,如①所示。AnnotationMethodHandlerAdapterBeanSpringMVCBeanBeanURLSpring2.5p命名空间,<property><bean><bean>让一Controller处理多个URL请SpringMVCMultiActionControllerControllerURL请求。使用@RequestMap注解后,这个功能更加容易实现了。请看下面的代码:3每个请求处理参数对应一个URLpackageimportimportorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;import publicclassBbtForumControllerprivateBbtForumService ("/listAllBoard.do")//<——publicStringlistAllBoard(){System.out.println("calllistAllBoardmethod.");return"listBoard";} ("/listBoardTopic.do")//<——publicStringlistBoardTopic(inttopicId){System.out.println("calllistBoardTopicmethod.");return"listTopic";}}在这里,我们分别在①和②处为listAllBoard()和listBoardTopic()方法标注了@RequestMap注解,分别指定这两个方法处理的URL请求,这相当于将BbtForumController改造为MultiActionController。这样/listAllBoard.doURL请求将由listAllBoard()负责处理,而/listBoardTopic.do?topicId=1的URLlistBoardTopic()4一个Controller对应一个URL,由请求参数决定请求处理方法对于处理多个URL请求的Controller来说,我们倾向于通过一个URL参数指定Controller(如method=listAllBoard而非直接通过不同的URL指定Controller的处理方法使用@RequestMap注packageimportimportorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller; ("/bbtForum.do")URLpublicclassBbtForumControllerprivateBbtForumServiceURL请求中包括"method=listAllBoard" (params=publicStringlistAllBoard(){System.out.println("calllistAllBoardmethod.");return"listBoard";}URL请求中包括"method=listBoardTopic"@RequestMap(params=publicStringlistBoardTopic(inttopicId){System.out.println("calllistBoardTopicmethod.");return"listTopic";}}在类定义处标注的@RequestMap让BbtForumController处理所有包含/bbtForum.do的URLBbtForumControllerURL照URL的method请求参数确定。所以分别在类定义处和方法定义处使用@RequestMap注解,就可以很容易通过URL参数指定Controller的处理方法了。5让请求处理方法处理特定的HTTP请求方法@RequestMapparamsmethodController方法处HTTPHTTPGETHTTPPOST请求,如packageimportimportorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMap;importorg.springframework.web.bind.annotation.RequestMethod;publicclassBbtForumController{@RequestMap(params="method=createTopic",method=publicStringcreateTopic(){System.out.println("callcreateTopicmethod.");return}}/bbtForum.do?method=createTopicHTTPPOST方式提交时,createTopic()才定URL参按契约绑Controller的方法标注了 注解后,它就能处理特定的URL请求URL5.按参数名匹配进行绑定 (params=①topicIdURLpublicStringlistBoardTopic(inttopicId){System.out.println("calllistBoardTopicmethod.");return"listTopic";}当我们发 的URL请求时,Spring不但让listBoardTopic方法处理这个请求,而且还将topicId请求参数在类型转换后绑定到listBoardTopic方法的topicId入参上。而listBoardTopic()方法的返回类型是String,它将被解析为逻辑视图的名称。也就是说Spring在如何给处理方法入参自动赋值以及如何将处理方法返回值转化为ModelAndView因此了解这个潜在规则无疑成为理解SpringMVC框架基于注解功能的问题。我们不妨从最常见的开始说起:请求处理方法入参的类型可以是Java基本数据类型或String类型,这时方法入参按参数名匹配的原则绑定到URL请求参数,同时还自动完成String类型的URL请求参数到请求处listBoardTopic(inttopicId)topicIdURLlistBoardTopic(inttopicId,StringboardName)topicId、boardNameURL,URL出TypeMismatchException异常,提示无法将null转换为基本数据类型。6.User.java:一个JavaBeanJavaBeanUserpackagepublicclassUser{privateintuserId;privateStringpublicStringreturnthis.userName}}7使用JavaBean作为请求处理方法的入参UserlistBoardTopic (params=publicStringlistBoardTopic(inttopicId,Useruser){System.out.println("calllistBoardTopicmethod.");return"listTopic";}URLtopicIdURLtopicIduserIduserNameURLuseruserIduserName和URL请求中不允许没有topicId参数不同,虽然User的userId属性的类型是基本数据类型,但如URLuserId参数,Springuser.userId0User对象拥有一个dept.deptId的级联属性,那么它将和dept.deptIdURL参数绑定。通过注解指定绑定的URL参如果我们想改变这种默认的按名称匹配的策略,比如让listBoardTopic(inttopicId,Useruser中的topicId绑定到id这个URL参数,那么可以通过对入参使用@RequestParam注解来达到目的:8通过@RequestParam注解指定这里,对listBoardTopic()请求处理方法的topicId入参标注了@RequestParam("id")idURLpackageimportorg.springframework.web.bind.annotation.RequestMap;importorg.springframework.web.bind.annotation.RequestParam;…publicclassBbtForumController{@RequestMap(params=publicStringlistBoardTopic(@RequestParam("id")intUseruser){System.out.println("calllistBoardTopicmethod.");return}…}这里@RequestParam注解可以用来提取名为“topicId”的int类型的参数,并将之作为输入参数传入。@RequestParamJava类型,你可通过定制PropertyEditors来扩展它的范围。下面是一些例子,其中包括了必需和可选参数:@RequestParam(value="number",required=false)Stringnumber@RequestParam("id")Longid@RequestParam("balance")double@RequestParamdouble注意,最后一个例子没有提供清晰的参数名。当且仅当代码带调试符号编译时,结果会提取名为“amount”的绑定模型对象中某个属性—Spring2.0定义了一个org.springframework.ui.ModelMap类,它作为通用的模型数据承载对象,9.使用ModelMap对应的隐含模型对象 (params=publicStringlistBoardTopic(@RequestParam("id")intUserModelMapmodel){publicpublicStringlistBoardTopic(@RequestParam("id")intUseruser,ModelMapmodel){System.out.println("topicId:"+topicId);System.out.println("user:"+user);;//packagepackage…importimport")publicclassBbtForumController… (params=System.out.println("topicId:"+topicId);System.out.println("user:"+user);//usercurrUsermodel中return"listTopic";}象上面的例子,ModelMap中的currUser属性将放到request的属性列表中,所以可以在JSP视图页面中通过request.getAttribute(“currUser”)或者通过${currUser}EL表达式模型对象中user对象。ModelMaprequest属性列表中添加对象的一条管道,借由ModelMap对象的支持,我们可以在一个不依赖ServletAPI的Controller中向request中添加属性。10使模型对象的特定属性具有Session范围的作用域在默认情况下,ModelMaprequest级别,也就是说,当本次请求结束后,ModelMap中的属性将销毁。如果希望在多个请求中共享ModelMap中的属性,必须将其属性转存到session中,这样ModelMap的属性才可以被跨请求。Spring允许我们有选择地指定ModelMap中的哪些属性需要转存到session中,以便下一个请求属对应的ModelMap的属性列表中还能到这些属性这能是通过类定义处标注@SessionAttributes注解来实现的。return}}我们在②处添加了一个ModelMap属性,其属性名为currUser@SessionAttributes注解ModelMapcurrUserSessionlistBoardTopic()请求所对应的JSPrequest.getAttribute(“currUser”)session.getAttribute(“currUser”)user对象,还JSPeon.geArbu(
)ea#ge(
currUser)")//publicclassBbtForumControllerprivate")//publicclassBbtForumControllerprivateBbtForumService(params=此外,@SessionAttributessessionModelMap属性:如@SessionAttributes(types=User.class),@SessionAttributes(types={11使模型对象的特定属性具有Session范围的作用域属性绑定到请求处理方法的入参中呢?答案是肯定的。Spring为此提供了一个@ModelAttribute的注解,下面是使用@ModelAttribute注解的例子return}@RequestMap(params=publicStringlistAllBoard(@ModelAttribute("currUser")Useruser){return}}在②处,我们向ModelMap中添加一个名为currUser的属性,currUsersession级的作用域。所以,@ModelAttributeModelMapcurrUser属性绑定以请求处理方法的user入参中。URL然后再以下URL:你将可以看到listAllBoard()的user入参已经成功绑定到listBoardTopic()中的currUser请求处理方法的签名规方法入我们知道标注了@RequestMap注解的Controller方法就成为了请求处理方法,SpringMVC允许极其灵活请求处理方法入参的可选类说Java默认情况下将按名称匹配的方式绑定到 L参数上,可以通过uPm注解改变默认的绑既可以是ServletAPI的也可以是PortletAPI对应的对象,Spring会将它们绑定到Portletrequest绑定到request对应的可以借此request的内java.io.OutputStream/response@RequestParam被标注@RequestParam注解的入参将绑定到特定的requestjava.util.Map/它绑定SpringMVC框架中每个请以被Web视图对象(如命令/表单对象(HTTPGETURL参数HTTPPOSTURL参数的到URL参数上,同时完成类型的转换。而类型转换的规则可以通过@InitBinder注解或通过为属性列表中令/表单对象的校可以通过该类型status对象显式结束表单的处理,这相当于触发session清除其中的通过SpringMVC框架的易用之处在于,你可以按任意顺序定义请求处理方法的入参(除了Errors和BindingResult必须紧跟在命令对象/表单参数后面以外,SpringMVC会根据反射机制自动将对应的对ServletAPI开发控制层的程序,当请求处理方法需要特定的对象时,仅仅需要在参数列表中入参即可,不需要考虑如何获取这些对象,Spring12使用SessionStatus控制Session级别的模型属性 (method=publicStringprocessSubmit(@ModelAttributeOwnerBindingResultSessionStatusstatus){//<——①newOwnerValidator().validate(owner,result);if(result.hasErrors())return}elsereturn"redirect:owner.do?ownerId="+}}processSubmitowner表单对象ModelMap的“owner”resultowner结果的对象,而status用于控制表单处理的状态。在②处,我们通过调用 plete()方法,该Controller所有放在session级别的模型属性数据将从session中清空。在默认情况下,ModelMaprequestModelMap中的属性将销毁。如果希望在多个请求中共享ModelMap中的属性,必须将其属性转存到session中,这样ModelMap的属性才可以被跨请求。Spring允许我们有选择地指定ModelMap中的哪些属性需要转存到session中,以便下一个请求属对应的ModelMap的属性列表中还能到这些属性这能是通过类定义处标注@SessionAttributes注解来实现的。10使模型对象的特定属性具有Session范围的作用域package…importimport")publicclassBbtForumController… (params=publicStringlistBoardTopic(@RequestParam("id")intUseruser,ModelMapmodel){System.out.println("topicId:"+topicId);System.out.println("user:"+user);;//return}}我们在②处添加了一个ModelMap属性,其属性名为currUser@SessionAttributes注解ModelMapcurrUserSessionlistBoardTopic()请求所对应的JSPrequest.getAttribute(“currUser”)session.getAttribute(“currUser”)user对象,还JSPeon.geArbu(
)ea#ge(
currUser)ModelMapSession中,其实@SessionAttributes允许指定多个属性:你可以通过字符串数组的方式指定多个属性,如@SessionAttributes({“attr1”,”attr2”})。此外,@SessionAttributessessionModelMap属性:如@SessionAttributes(types=User.class),@SessionAttributes(types={11使模型对象的特定属性具有Session范围的作用域属性绑定到请求处理方法的入参中呢?答案是肯定的。Spring为此提供了一个@ModelAttribute的注解,下面是使用@ModelAttribute注解的例子")//publicclassBbtForumControllerprivateBbtForumService@RequestMap(params=publicStringlistBoardTopic(@RequestParam("id")intUseruser,ModelMapmodel){System.out.println("topicId:"+topicId);System.out.println("user:"+user);;return}@RequestMap(params=publicStringlistAllBoard(@ModelAttribute("currUser")Useruser)return"listBoard";}}在②处,我们向ModelMap中添加一个名为currUser的属性,currUsersession级的作用域。@ModelAttributeModelMapcurrUser属性绑定以请求处理方法的user入参中。所以当我们先调用以下URL请求:然后再以下URL:你将可以看到listAllBoard()的user入参已经成功绑定到listBoardTopic()中的currUser方法返回参SpringMVCModelAndView。而在Spring2.5中,你拥有多种灵活的选择。通过下表进行说明:URL publicvoid eHandler(){} (method=RequestMethod.GET)publicStringsetupForm(@RequestParam("ownerId")intownerId,ModelMapmodel){ return"ownerForm";}voidURL,如下publicModelMapvetsHandler()returnnew}vets的模型对象,可以在JSP视图页面中到。String作为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求URLModelMapModelAndView如何准备数据--在编写Controller时,常常需要在真正进入请求处理方法前准备一些数据,以便请求处理或视图渲染时使用。在传统的SimpleFormController里,是通过复写其referenceData()方法来准备数据的。Spring2.5@ModelAttribute,使其返回值将会进入到6.116.定义为处理请求准备数据的方importorg.springframework.web.bind.annotation.SessionAttributes;importjava.util.ArrayList;importjava.util.List;importjava.util.Set;publicclassBbtForumController{privateBbtForumServicepublicList<String>populateItems(){List<String>lists=newArrayList<String>();returnlists;}@RequestMap(params=publicString@ModelAttribute("currUser")Useruser,ModelMapmodel){return"listBoard";}}说明在①处,通过使用@ModelAttribute注解,populateItem()方法将在任何请求处理方法执行前调用,SpringMVC会将该方法返回值以“items”为名放入到隐含的模型对象属性列表中。所以在②处,我们就可以通过ModelMap入参到items属性,当执行listAllBoard()请求处理方法时,②处将在控制台打印出“model.items:2”的信息。当当然我们也可以在请求的视图 到模型对象中的items属性@MVCSpringMVC使用@MVC,除了由于@ModelAttribute、@InitBinder和@SessionAttributes这些注解的存在而@ModelAttribute注 publicAccountsetupForm(){} publicvoidonSubmit(Accountaccount){}HTTPGET请求,准备被编辑的数据,返回Account对象SpringMVC表单标HTTPPOST请求,并接收一个AccountAccount<form:formmodelAttribute="account"AccountNumber:<form:inputpath="number"/><form:errors是因为@MVC用返回对象的类型名称作为默认值,因此一个Account类型的对象默认的就对应一个名为public@ModelAttribute("account")SpecialAccountsetupForm()} publicvoidupdate(@ModelAttribute("account")SpecialAccountaccount)}setupForm()不是一个请求处理方法,而是任何请求处理方法被调用之前,用来准备表单项模型对象的一个方法。对那些熟悉SpringMVC的老用户来说,这和SimpleFormController的做的改变覆盖已有的Account对象时,我们会第二次得到它,在这种表单处理场景中把@ModelAttribute放(session用@SessionAttributes属publicclassAccountFormController}@SessionAttributes(types=publicclassAccountFormController}根据上面的注解,AccountFormControllerGETPOST方法之间,把名为SessionStatus实例来做这件事,如果把它添加进onSubmit的方法签名中,@MVC会完成这个任务: publicvoidonSubmit(Accountaccount,SessionStatussessionStatus) plete();//Clears}雁联例效果图“修改页面(modifyProcess.jsp)”上会显示该条记录的信息(根据ID从数据库记录,然后显示在页面遇到的问题上显示的不是“修改后”的信息,而还是“修改前”的信息。“修改页面(modifyProcess.jsp)head<metahttp-equiv="pragma"content="no-<metahttp-equiv="cache-control"content="no-<metahttp-equiv="expires"<base<scripttype="text/javascript"<link “subProcess.jsp,“修改”<td<inputtype="button"name="Submitvalue="修改"publicclassSubSysProControllerprivatepublicclassSubSysProControllerprivateValidator(params="method=modifyProcUI",method=publicStringmodifyProcUI(Processprocess,BindingResultresult,Model{if(result.hasErrors())return}process=processService.getProcessById(process.getId());List<SubSys>subSysList=model.addAttribute("process",process);model.addAttribute("subSysList",subSysList);return"processManage/processModify";}}<beansxmlns=" ponent-scanbase-<bean><property<bean<bean <propertyname="validatorFactory"<bean <property<metahttp-equiv="pragma"content="no-<metahttp-equiv="cache-control"content="no-<metahttp-equiv="expires"<base<form:form<tableclass=tb_inputcellspacing=1<tdwidth="15%nowrapclass="td_title"><spanclass="fond_b<form:inputpath="imageName"cssStyle="WIDTH:<form:errorspath="imageName"<tdnowrap<form:inputcssStyle="WIDTH:180px"<tdnowrapclass="td_title"><form:inputcssStyle="WIDTH:180px"<tdnowrap<spanclass="fond_b<form:selectpath="subSys.id"cssStyle="WIDTH:<form:option<form:optionsitemLabel="code"<form:errorspath="subSys.id"<inputtype="buttonclass="buttononclick="save()value="修改进程<inputtype="button"value="取消class="buttonfunctionsave().forms[0].action="<c:urlvalue='/procAdmin/subSysProc'/>";}定制数据绑定--@InitBinder注PropertyEditors。用@MVC实现这些功能是非常容易的:publicvoidinitDataBinder(WebDataBinderbinder)binder.setRequiredFields(newString[]{"number",}@InitBinder注解的方法可以@MVC用来绑定请求参数的DataBinder实例,它允许我们为每个例1.自己的属性编辑SpringMVC有一套常用的属性编辑器,这包括基本数据类型及其包裹类的属性编辑器、String属性编辑器、JavaBean的属性编辑器等。但有时我们还需要向SpringMVC框架一些自定义的属性编辑器,SpringMVC允许向整个Spring框架属性编辑器,它们对所有Controller都有影响当然SpringMVC也允许仅向某个Controller属性编辑器,对其它的Controller没有影响。前者可以通过AnnotationMethodHandlerAdapter的配置做到,而后者则可以通过@InitBinder例1:下面先看向整个SpringMVC框架的自定义编辑器13.框架级的自定义属性编辑器<bean<property<bean14.自定义属性编辑器--配置一个定制的WebBindingInitializer一个AnnotationMethodHandlerAdapter提供一个定制的bean配置可以使它启用,这样就覆盖了默认配例子:MyBindingInitializerWebBindingInitializer接口接口方法binder多个自定义的属性编辑器.java.util.DateCustomDateEditor。其代packageimportjava.text.SimpleDateFormat;importjava.util.Date;importorg.springframework.beans.factory.annotation.Autowired;pertyeditors.CustomDateEditor;pertyeditors.StringTrimmerEditor;importorg.springframework.samples.petclinic.Clinic;importorg.springframework.samples.petclinic.PetType;importorg.springframework.web.bind.WebDataBinder;importimportpublicclassMyBindingInitializerimplementsWebBindingInitializerpublicvoidinitBinder(WebDataBinderbinder,WebRequestrequest){SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd");Date.class,newCustomDateEditor(dateFormat,String.class,new}}如果希望某个属性编辑器仅作用于特定的Controller,可以在Controller中定义一个标注@InitBinder注解的方法,可以在该方法中向Controller了若干个属性编辑器使用@InitBinder控制器方法,可以在控制器类Web数据绑定@InitBinder指定初始化WebDataBinder的方法,后者被用于填充注解的句柄方法令和表单对 果对象。 典型的参数,包Init-binder方法必须没有返回值。因此,它们常 为voidInit-binder方法必须没有返回值。因此,它们常 为void15.Controller级的自定义属性编辑器注意:被标注@InitBinder注解的方法必须拥有一个WebDataBinder类型的入参,以便Spring框架将属性编辑器的WebDataBinder对象传递进来publicclassMyFormControllerpublicvoidinitBinder(WebDataBinderbinder)SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd");//binder.setRequiredFields(newString[]{"number",}…}数据绑定结果和验证--也许会导致类似于类型转换或域缺失方法签名的表单模型对象BindingResult对象(注意检验结果 publicModelAndViewonSubmit(Accountaccount,BindingResultbindingResult){if(bindingResult.hasErrors()){ModelAndViewmav=newModelAndView();returnmav;}//Savethechangesandredirecttothenext}DispatcherServlet依靠与URI路径信息匹配的默认视图名。 publicModelAndViewonSubmit(Accountaccount,BindingResultbindingResult){newAccountValidator().validate(account,bindingResult);if(bindingResult.hasErrors()){ModelAndViewmav=newModelAndView();returnmav;}//Savethechangesandredirecttothenext}publicclassAccountValidatorpublicvoidvalidate(Ownerowner,Errorserrors)if(!StringUtils.hasLength(owner.getFirstName()))errors.rejectValue("firstName","required",}if(!StringUtils.hasLength(owner.getLastName()))errors.rejectValue("lastName","required",}if(!StringUtils.hasLength(owner.getAddress()))errors.rejectValue("address","required",}if(!StringUtils.hasLength(owner.getCity()))errors.rejectValue("city","required",}Stringephone=owner.getif(!StringUtils.hasLength(e
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年中国汽车水箱烘焊炉市场调查研究报告
- 2025年中国抽桶市场调查研究报告
- 支架术后定期复查与随访管理
- 特别护理记录单的国际化趋势
- 人工智能辅助护理技术
- 药物过敏的护理创新方法
- 卧床老人心理障碍护理与干预
- 给排水工程施工方案
- 护理专业能力评估中的跨专业合作
- 痔疮术后个人卫生护理技巧
- 人教部编版道德与法治八年级下册道德与法治期末测试检测试题(解析版)
- 2024年北京中考语文试题及答案
- 新青岛版-二年级下册数学-口算题
- 周志华-机器学习-Chap01绪论-课件
- X矿业企业120万t选矿厂投标文件技术标
- 汉语写作与百科知识样题
- 提高喷射混凝土施工一次验收合格率QC成果
- 美丽中国(支教项目)
- 题型01 长句表达题的规范答题(课件) 高考生物二轮复习 (新教材专用)
- GB/T 17467-2020高压/低压预装式变电站
- 新通用设备经济寿命参考年限表
评论
0/150
提交评论