版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
附录A外文翻译—原文部分F.Gutierrez,ProSpringBoot2WebApplicationswithSpringBootNowadays,thewebisthemainchannelforanytypeofapplication—fromdesktoptomobiledevices,fromsocialandbusinessapplicationstogames,andfromsimplecontenttostreamingdata.Withthisismind,SpringBootcanhelpyoueasilydevelopthenextgenerationofwebapplications.ThischaptershowsyouhowtocreateSpringBootwebapplicationswithease.Youhavealreadylearned,withsomeexamplesinearlierchapters,whatyoucandowiththeweb.YoulearnedthatSpringBootmakesiteasiertocreatewebappswithafewlinesofcodeandthatyoudon’tneedtoworryaboutconfigurationfilesorlookforanapplicationservertodeployyourwebapplication.ByusingSpringBootanditsauto-¬configuration,youcanhaveanembeddedapplicationserver,suchasTomcat,Nettie,Undertow,orJetty,whichmakesyourappverydistributableandportable.SpringMVCLet’sstarttalkingabouttheSpringMVCtechnologyandsomeofitsfeatures.RememberthattheSpringFrameworkconsistsofabout20modulesortechnologies,andthewebtechnologyisoneofthem.Forthewebtechnology,theSpringFrameworkhasthespring-web,spring-webmvc,spring-webflux,andspring-websocketmodules.Thespring-webmodulehasbasicwebintegrationfeatures,suchasmultipartfileuploadfunctionality,initializationoftheSpringcontainer(byusingservletlisteners),andaweb-orientedapplicationcontext.Thespring-mvcmodule(a.k.a.,thewebservermodule)containsalltheSpringMVC(Model-View-Controller)andRESTservicesimplementationsforwebapplications.Thesemodulesprovidemanyfeatures,suchasverypowerfulJSPtaglibraries,customizablebindingandvalidation,flexiblemodeltransfer,customizablehandlerandviewresolution,andsoon.TheSpringMVCisdesignedaroundtheorg.springframework.web.servlet.DispatcherServletclass.Thisservletisveryflexibleandhasaveryrobustfunctionalitythatyouwon’tfindinanyotherMVCwebframeworkoutthere.WiththeDispatcherServlet,youhaveseveralout-of-the-boxresolutionsstrategies,includingviewresolvers,localeresolvers,themeresolvers,andexceptionhandlers.Inotherwords,theDispatcherServlettakeaHTTPrequestandredirectittotherighthandler(theclassmarkedwiththe@Controlleror@RestControllerandthemethodsthatusethe@RequestMappingannotations)andtherightview(yourJSPs).SpringBootMVCAuto-ConfigurationWebapplicationscanbecreatedeasilybyaddingthespring-boot-starter-webdependencytoyourpom.xmlorbuildgradlefile.Thisdependencyprovidesallthenecessaryspring-webjarsandsomeextraones,suchastomcat-embed*andjackson(forJSONandXML).ThismeansthatSpringBootusesthepoweroftheSpringMVCmodulesandprovidesallthenecessaryauto-configurationforcreatingtherightwebinfrastructure,suchasconfiguringtheDispatcherServlet,providingdefaults(unlessyouoverrideit),settingupanembeddedTomcatserver(soyoucanrunyourapplicationwithoutanyapplicationcontainers),andmore.Auto-configurationaddsthefollowingfeaturestoyourwebapplication.Staticcontentsupport.Thismeansthatyoucanaddstaticcontent,suchasHTML,JavaScript,CSS,media,andsoforth,inadirectorynamed/static(bydefault)or/public,/resources,or/META-INF/resources,whichshouldbeinyouclasspathorinyourcurrentdirectory.SpringBootpicksitupandservesthemuponrequest.Youcanchangethiseasilybymodifyingthespring.mvc.static-path-¬patternorthespring.resources.static-locationsproperties.OneofthecoolfeatureswithSpringBootandwebapplicationsisthatifyoucreateanindex.htmlfile,SpringBootservesitautomaticallywithoutregisteringanyotherbeanortheneedforextraconfiguration. HttpMessageConverters.IfyouareusingaregularSpringMVCapplicationandyouwanttogetaJSONresponse,youneedtocreatethenecessaryconfiguration(XMLorJavaConfig)fortheHttpMessageConvertersbean.SpringBootaddsthissupportbydefaultsoyoudon’thaveto;thismeansthatyougettheJSONformatbydefault(duetotheJacksonlibrariesthatthespring-¬boot-starter-webprovidesasdependencies).AndifSpringBootauto-configurationfindsthatyouhavetheJacksonXMLextensioninyouclasspath,itaggregatesanXMLHttpMessageConvertertotheconverters,meaningthatyourapplicationcanserverbasedonyourcontent-typerequest,eitherapplication/jsonorapplication/xml.•JSONserializersanddeserializers.Ifyouwanttohavemorecontrolovertheserialization/deserializationto/fromJSON,SpringBootprovidesaneasywaytocreateyourownbyextendingfromJsonSerializer<T>andJsonDeserializer<T>,andannotatingyourclasswiththe@JsonComponentsothatitcanberegisteredforusage.AnotherfeatureofSpringBootistheJacksonsupport;bydefault,SpringBootserializesthedatefieldsas2018-05-01T23:31:38.141+0000,butyoucanchangethisdefaultbehaviorbychangingthespring.jackson.date-format=yyyy-MM-ddproperty(youcanapplyanydateformatpattern);thepreviousvaluegeneratestheoutput,suchas2018-05-01.•Pathmatchingandcontentnegotiation.OneoftheSpringMVCapplicationpracticesistheabilitytorespondtoanysuffixtorepresentthecontent-typeresponseanditscontentnegotiation.Ifyouhavesomethinglike/api/todo.jsonor/api/todo.pdf,thecontent-typeissettoapplication/jsonandapplication/pdf;sotheresponseisJSONformatoraPDFfile,respectively.Inotherwords,SpringMVCperforms.*suffixpatternmatching,suchas/api/todo.*.SpringBootdisablesthisbydefault.Youcanstilluseafeaturewhereyoucanaddaparameter,byusingthespring.mvc.contentnegotiation.favor-parameter=trueproperty(falsebydefault);soyoucandosomethinglike/api/todo?format=xml.(formatisthedefaultparametername;ofcourse,youcanchangeitwithspring.mvc.contentnegotiation.parameter-name=myparam).Thistriggersthecontent-typetoapplication/xml.•Errorhandling.SpringBootuses/errormappingtocreateawhitelabeledpagetoshowalltheglobalerrors.Youcanchangethebehaviorbycreatingyourowncustompages.YouneedtocreateyourcustomHTMLpageinthesrc/main/resources/public/error/location,soyoucancreate500.htmlor404.htmlpagesforexample.IfyouarecreatingaRESTfulapplication,SpringBootrespondsasJSONformat.SpringBootalsosupportsSpringMVCtohandleerrorswhenyouareusing@ControllerAdviceor@ExceptionHandlerannotations.YoucanregistercustomErrorPagesbyimplementingErrorPageRegistraranddeclaringitasaSpringbean.•Templateenginesupport.SpringBootsupportsFreeMarker,GroovyTemplates,Thymeleaf,andMustache.Whenyouincludethespring-¬boot-starter-<templateengine>dependency,SpringBootauto-configureisnecessarytoenableandaddallthenecessaryviewresolversandfilehandlers.Bydefault,SpringBootlooksatthesrc/main/resources/templates/path.AndtherearemanyotherfeaturesthatSpringBootWebauto-configureprovides.Rightnow,weareonlylookingattheServlettechnology,butverysoonwegetintothenewestadditiontotheSpringBootfamily:WebFlux.SpringBootWeb:ToDoAppTobetterunderstandhowSpringBootworkswithwebapplicationsandthepoweroftheSpringMVCmodules,youaregoingtocreateaToDoappthatexposesaRESTfulAPI.Thesearetherequirements:•CreateaToDodomainmodelthathasthefollowingfieldsandtypes:id(String),description(String),completed(Boolean),created(datewithtime),modified(datewithtime).•CreateaRESTfulAPIthatprovidesthebasicCRUD(create,read,update,delete)actions.UsethemostcommonHTTPmethods:POST,PUT,PATCH,GET,andDELETE.•CreatearepositorythathandlesthestateofmultipleToDo’s.Fornow,anin-memoryrepositoryisenough.•AddanerrorhandlerwhenthereisabadrequestorwhensubmittinganewToDodoesn’thavetherequiredfields.Theonlymandatoryfieldisthedescription.•AlltherequestsandresponsesshouldbeinJSONformat.ToDoAppOpenyourbrowserandgotohttps://start.spring.iotocreateyourToDoappbyusingthefollowingvalues.•Group:com.apress.todo•Artifact:todo-in-memory•Name:todo-in-memory•PackageName:com.apress.todo•Dependencies:Web,LombokChoosingtheLombokdependencyhelpseasilycreatethedomainmodelclassesandeliminatestheboilerplatesetters,getters,andotheroverrides.YoucanselecteitherMavenorGradleastheprojecttype;inthisbook,weusebothindistinctly.PresstheGenerateProjectbuttonanddownloadtheZIPfile.UncompressitandimportitintoyourfavoriteIDE.SomeofthebestIDEsareSTS(https://spring.io/tools/sts/all),IntelliJIDEA(/idea/),andVSCod(/).IrecommendoneoftheseIDEsforthecodecompletionfeature,whichhelpsyouseethemethodsorparameterstoaddtoyourcode.DomainModel:ToDoBasedontherequirements,youneedtocreateaToDodomainmodelclass.showsyoutheToDoclass,whichhasalltherequiredfields.Italsousesthe@Dataannotation,whichisaLombokannotationthatgeneratesadefaultconstructor(ifyoudon’thaveone)andallthesetters,getters,andoverrides,suchasthetoStringmethod,tomaketheclasscleaner.Alsonotethattheclasshasthe@NotNulland@NotBlankannotationsinsomeofthefields;theseannotationsareusedinthevalidationthatwedolateron.Thedefaultconstructorhasfieldinitialization,soitiseasytocreateaToDoinstance.FluentAPI:ToDoBuilderNextlet’screateaFluentAPIclassthathelpscreateaToDoinstance.YoucanseethisclassafactorythatcreatesaToDowithadescriptionorwithaparticularID.Repository:CommonRepository<T>.Next,createaninterfacethathascommonpersistenceactions.Thisinterfaceisgeneric,soiteasytouseanyotherimplementation,makingtherepoanextensiblesolution.Thereisacommoninterfacethatcanbeusedasabaseforanyotherpersistenceimplementation.Ofcourse,youcanchangethesesignaturesatanytime.Thisisjustanexampleonhowtocreatesomethingthatisextensible.Repository:ToDoRepositoryLet’screateaconcreteclassthatimplementstheCommonRepository<T>interface.Rememberthespecification;fornow,itisnecessaryonlytohavetheToDo’sinmemoryshowstheimplementationoftheCommonRepository<T>interface.Reviewthecodeandanalyzeit.ThisclassisusingahashthatholdsalltheToDo’s.Alltheoperationsgetsimplifyduenatureofthehash,makingiteasytoimplement.Validation:ToDoValidationErrorNext,let’screateavalidationclassthatexposesanypossibleerrorsintheapp,suchasaToDowithnodescription.RememberthatintheToDoclass,theIDanddescriptionfieldsaremarkedas@NotNull.Thedescriptionfieldhasanextra@NotBlankannotationtomakesurethatitisneveremptyshowstheToDoValidationErrorclass,whichholdsanyerrorsthatarisewithanyrequests.Itusesanextra@JsonIncludeannotation,whichsaysthateveniftheerrorsfieldisempty,itmustbeincluded.Controller:ToDoControllerNow,it’stimetocreatetheRESTfulAPIanduseallthepreviousclasses.YoucreatetheToDoControllerclass,inwhichyouseealltheSpringMVCfeatures,theannotations,thewaytoconfigureendpoints,andhowtohandleerrors.•@RestController.SpringMVCoffersthe@Controllerand@RestControllertoexpressrequestmappings,requestinput,exceptionhandling,andmore.Allthefunctionalityreliesontheseannotations,sothereisnoneedtoextendorimplementinterfacesspecificinterfaces.•@RequestMapping.Thisannotationmapsrequeststocontrollermethods.ThereareseveralattributestomatchURLs,HTTPmethods(GET,PUT,DELETE,etc.),requestparameters,headers,andmediatypes.Itcanbeuseatclasslevel(tosharemappings)oratmethodlevelforspecificendpointmapping.Inthiscase,itismarkedwith"/api",meaningthatallthemethodshavethisprefix.•@Autowired.Theconstructorisannotatedwith@Autowired,meaningthatitinjectstheCommonRepository<ToDo>implementation.Thisannotationcanbeomitted;Springautomaticallyinjectsanydeclareddependencysinceversion4.3.•@GetMapping.Thisisashortcutvariantofthe@RequestMappingannotation,usefulforHTTPGETmethods.@GetMappingisequivalentto@RequestMapping(value="/todo",method={RequestMethod.GET}).•@PatchMapping.Thisisashortcutvariantofthe@RequestMappingannotation;inthisclass,itmarksaToDoascompleted.•@DeleteMapping.Thisisashortcutvariantofthe@RequestMappingannotation;itisusedtodeleteaToDo.Therearetwooverloadmethods:deleteToDo,oneacceptingaStringandtheotheraToDoinstance.•@PathVariable.ThisannotationisusefulwhenyoudeclareanendpointthatcontainsaURLexpressionpattern;inthiscase,"/api/todo/{id}",wheretheIDmustmatchthenameofthemethodparameter.•@RequestBody.Thisannotationsendsarequestwithabody.Normally,whenyousubmitaformoraparticularcontent,thisclassreceivesaJSONformatToDo,thentheHttpMessageConverterdeserializestheJSONintoaToDoinstance;thisisdoneautomaticallythankstoSpringBootanditsauto-configurationbecauseitregisterstheMappingJackson2HttpMessageConverterbydefault.•ResponseEntity<T>.Thisclassreturnsafullresponse,includingHTTPheaders,andthebodyisconvertedthroughHttpMessageConvertersandwrittentotheHTTPresponse.TheResponseEntity<T>classsupportsafluentAPI,soitiseasytocreatetheresponse.•@ResponseStatus.Normally,thisannotationisusedwhenamethodhasavoidreturntype(ornullreturnvalue).ThisannotationsendsbacktheHTTPstatuscodespecifiedintheresponse.•@Valid.Thisannotationvalidatesincomingdataandisusedasamethod’sparameters.Totriggeravalidator,itisnecessarytoannotatethedatayouwanttovalidatewith@NotNull,@NotBlank,andotherannotations.Inthiscase,theToDoclassusesthoseannotationsintheIDanddescriptionfields.Ifthevalidatorfindserrors,theyarecollectedintheErrorsclass(inthiscase,ahibernatevalidatorthatcamewiththespring-webmvcjarsisregisteredandusedasaglobalvalidator;youcancreateyourowncustomvalidationandoverrideSpringBoot’sdefaults).Thenyoucaninspectandaddthenecessarylogictosendbackanerrorresponse.•@ExceptionHandler.TheSpringMVCautomaticallydeclaresbuilt-inresolversforexceptionsandaddsthesupporttothisannotation.Inthiscase,the@ExceptionHandlerisdeclaredinsidethiscontrollerclass(oryoucanuseitwithina@ControllerAdviceinterceptor)andanyexceptionisredirectedtothehandleExceptionmethod.Youcanbemorespecificifneeded.Forexample,youcanhaveaDataAccessExceptionandhandlethroughamethod.IntheclassthereisamethodthatacceptstwoHTTPmethods:POSTandPUT.@RequestMappingcanacceptmultipleHTTPmethods,soitiseasytoassignonemethodtoprocessthem(e.g.,@RequestMapping(value="/todo",method={RequestMethod.POST,RequestMethod.PUT}).Wehavecoveredallthenecessaryrequirementsforthisapplication,soit’stimetorunitandseetheresults.Running:ToDoAppNow,youarereadytoruntheToDoappandtestit.IfyouareusinganIDE(STSorIntelliJ),youcanright-clickthemainappclass(TodoInMemoryApplication.java)andselectRunAction.Ifyouareusinganeditorthatdoesn’thavethesefeatures,youcanrunyourTodoappbyopeningaterminalwindowandexecutingthecommands.SpringInitializr(https://start.spring.io)alwaysprovidestheprojecttypewrappersyouselected(MavenorGradlewrappers),sothereisnoneedtopreinstallMavenorGradle.OneofdefaultsforSpringBootwebappsisthatitconfiguresanembeddedTomcatserver,soyoucaneasilyrunyourappwithoutdeployingittoanapplicationservletcontainer.Bydefault,itchoosesport8080.Testing:ToDoAppTestingtheToDoappshouldbeverysimple.Thistestingisthroughcommandsoraspecificclient.Ifyouarethinkingaboutunitorintegrationtesting,I’llexplainthatinanotherchapter.HerewearegoingtousethecURLcommand.ThiscommandcomesinanyUNIXOSflavorbydefault,butifyouareaWindowsuser,youcandownloaditfromhttps://curl.haxx.se/download.html.Whenrunningforthefirsttime,theToDoappshouldn’thaveanyToDo’s.Youcanmakesureofthisbyexecutingthefollowingcommandinanotherterminal.curl-ihttp://localhost:8080/api/todoYoushouldseesomethingsimilartothisoutput:HTTP/1.1200Content-Type:application/json;charset=UTF-8Transfer-Encoding:chunkedDate:Wed,02May201822:10:19GMTYouaretargetingthe/api/todoendpoint,andifyoutakealookatListing4-7,agetToDosmethodreturnsResponseEntity<Iterable<ToDo>>,whichisacollectionofToDo’s.ThedefaultresponseisaJSONformat(seetheContent-Typeheader).TheresponseissendingbacktheHTTPheadersandstatus.Next,let’saddsomeToDo’swiththefollowingcommand.curl-i-XPOST-H"Content-Type:application/json"-d'{"description":"ReadtheProSpringBoot2ndEditionBook"}'http://localhost:8080/api/todoInthecommand,post(-XPOST)anddata(-d)areJSONformat.Youaresendingonlythedescriptionfield.Itisnecessarytoaddtheheader(-H)withtherightcontent-¬type,andpointtothe/api/todoendpoint.Afterexecutingthecommand.Yougetbackthelocationheader,wheretheToDoisread.LocationexposestheIDoftheToDoyouhavejustcreated.ThisresponsewasgeneratedbythecreateToDomethod.AddatleastanothertwoToDo’ssothatwecanhavemoredata.HereTakethedogforawalkischangedtoTakethedogandthecatforawalk.Thecommandisusingthe-XPUTandtheidfieldisneeded(wecangetitfromthelocationheaderfrompreviousPOSTsorfromaccessingthe/api/todoendpoint).IfyoureviewalltheToDo’s,youhaveamodifiedToDo.Next,let’scompleteaToDo.Youcanexecutethefollowingcommand.Thecommandisusingthe-XPATCHthatprocessbythesetCompletedmethod.Ifyoureviewthelocationlink,ToDoshouldbecompletedThecompletedfieldisnowtrue.IfthisToDoiscompleted,thenyoucandeleteit.curl-i-XDELETEhttp://localhost:8080/api/todo/2d051b67-7716-4ee6-9c45-1de939fa579fHTTP/1.1204Date:Wed,02May201822:56:18GMTThecURLcommandhas-XDELETE,whichisprocessedbythedeleteToDomethod,removingitfromthehash.IfyoutakealookatalltheToDo’s,youshouldnowhaveonelessthanbefore.A400statuscode(BadRequest)andtheerrorsanderrorMessage(builtbytheToDoValidationErrorBuilderclass)response.Usethefollowingcommand.curl-i-XPOST-H"Content-Type:application/json"http://localhost:8080/api/todoThiscommandispostingbutnodataandisrespondingwithanerrormessage.Thisisfromthe@ExceptionHandlerannotationandthehandleExceptionmethod.Alltheerrors(differentfromthedescriptionbeingblank)arehandledbythismethod.YoucankeeptestingmoreToDo’sormodifysomeofthevalidationannotationstoseehowtheywork.NoteIfyoudon’thavethecURLcommandoryoucan’tinstallit,youcanuseanyotherRESTclient,suchasPostMan()orInsomnia(https://insomnia.rest).Ifyoulikecommandlines,thenHttpie()isanothergoodoption;itusesPython.SpringBootWeb:OverridingDefaultsSpringBootwebauto-configurationsetsdefaultstorunaSpringwebapplication.Inthissection,Ishowyouhowtooverridesomeofthem.Youcanoverridethewebdefaultsbyeithercreatingyourownconfiguration(XMLorJavaConfig)and/pertiesorymlfile.ServerOverridingbydefault,theembeddedTomcatserverstartsonport:8080,butyoucaneasilychangethatbyusingtheproperty.OneofthecoolfeaturesofSpringisthatyoucanapplytheSpEL(SpringExpressionLanguage)andapplyittotheseproperties.Forexample,whenyoucreateanexecutablejar(./mvnwpackageor./gradlewbuild),youcanpasssomeparameterswhenrunningyourapplication.Thisexpressionmeansthatifyoupassthe--portargument,ittakesthatvalue;ifnot,itssetto8282.ThisisjustasmalltasteofwhatyoucandowithSpEL.
附录B外文翻译—译文部分SpringBoot的Web应用程序如今,网络是任何类型应用程序的主要渠道,从桌面到移动设备,从社交和商业应用程序到游戏,从简单内容到流数据。有了这个想法,SpringBoot可以帮助您轻松开发下一代Web应用程序。本文将介绍如何轻松创建SpringBootWeb应用程序。已经通过前面一些示例了解了可以使用Web做什么。了解到SpringBoot可以更轻松地使用几行代码创建Web应用程序,并且无需担心配置文件或寻找应用程序服务器来部署Web应用程序。通过使用SpringBoot及其自动配置,可以拥有一个嵌入式应用程序服务器,如Tomcat,Nettie,Undertow或Jetty,这使得应用程序可以非常易于分发和移植。SpringMVC现在开始讨论SpringMVC技术及其一些功能。请记住,SpringFramework包含大约20个模块或技术,Web技术就是其中之一。对于Web技术,SpringFramework具有spring-web,spring-webmvc,spring-webflux和spring-websocket模块。spring-web模块具有基本的Web集成功能,例如多部分文件上载功能,Spring容器的初始化(通过使用servlet侦听器)和面向Web的应用程序上下文。spring-mvc模块(也就是Web服务器模块)包含Web应用程序的所有SpringMVC(模型-视图-控制器)和REST服务实现。这些模块提供了许多功能,例如非常强大的JSP标记库,可自定义的绑定和验证,灵活的模型传输,可自定义的处理程序和视图分辨率等。SpringMVC是围绕org.springframework.web.servlet设计的。DispatcherServlet类。这个servlet非常灵活,并且具有非常强大的功能,在任何其他MVCWeb框架中都找不到。使用DispatcherServlet,您可以使用多种开箱即用的解析策略,包括视图解析器,区域设置解析器,主题解析器和异常处理程序。换句话说,DispatcherServlet接受HTTP请求并将其重定向到正确的处理程序(标记为@Controller或@RestController的类以及使用@RequestMapping注释的方法)。SpringBootMVC自动配置通过将spring-boot-starter-web依赖项添加到pom.xml或build.gradle文件,可以轻松创建Web应用程序。这种依赖提供了所有必需的spring-webjar和一些额外的jar,例如tomcat-embed*和jackson(用于JSON和XML)。这意味着SpringBoot使用SpringMVC模块的强大功能,并提供所有必要的自动配置,以创建正确的Web基础结构,例如配置DispatcherServlet,提供默认值(除非您覆盖它),设置嵌入式Tomcat服务器(所以你可以在没有任何应用程序容器的情况下运行应用程序)等等。自动配置会将以下功能添加到Web应用程序中:•静态内容支持。这意味着您可以添加静态内容,如导演中的HTML,JavaScript,CSS,媒体等等named/static(默认情况下)或/public,/resources或/META-INF/资源,应该在您的类路径或当前directory.SpringBoot选择它并根据请求提供它们。你可以通过修改spring.mvc.static-path-来轻松改变这一点pattern或spring.resources.static-locations属性。SpringBoot和Web应用程序的一个很酷的功能如果你创建一个index.html文件,SpringBoot会为它提供服务自动无需注册任何其他bean或需要额外的组态。•Http消息转换器。如果您使用常规的SpringMVC应用程序,您需要获得ISON响应。创建必要的配置(XML或JavaConfig)将Http消息转换成bean,SpringBoot默认添加此支持,因此您不必这样做;这意味着您默认获得JSON格式(由于spring-boot-starter-web提供的Jackson库作为依赖项)。如果SpringBoot自动配置发现您在类路径中有JacksonXML扩展,它会将XMLHttpMessageConverter聚合到转换器,这意味着您的应用程序可以根据您的内容类型请求(application/json或application/xml)进行服务。•JSON序列化程序和反序列化程序。如果你想对JSON的序列化/反序列化有更多的控制,SpringBoot提供了一种简单的方法来创建你自己的,通过从JsonSerializer<T>和JsonDeserializer<T>扩展,并使用@JsonComponent注释你的类,以便它可以注册用法。SpringBoot的另一个特色是杰克逊的支持;默认情况下,SpringBoot将日期字段序列化为2018-05-01T23:31:38.141+0000,但您可以通过更改spring.jackson.date-format=yyyy-MM-dd属性来更改此默认行为(您可以应用任何日期格式图案);上一个值生成输出,例如2018-05-01。•路径匹配和内容协商。SpringMVC应用程序实践之一是能够响应任何后缀以表示内容类型响应及其内容协商。如果您有/api/todo.json或/api/todo.pdf之类的内容,则将content-type设置为application/json和application/pdf;所以响应分别是JSON格式或PDF文件。换句话说,SpringMVC执行.*后缀模式匹配,例如/api/todo.*.SpringBoot默认禁用此功能。您仍然可以使用spring.mvc.contentnegotiation.favor-parameter=true属性添加参数的功能(默认为false);所以你可以做/api/todo?format=xml。(format是默认参数名称;当然,您可以使用spring.mvc.contentnegotiation.parameter-name=myparam更改它。这会触发content-type到application/xml。•错误处理。SpringBoot使用/error映射创建一个白色标记页面以显示所有全局错误。您可以通过创建自己的自定义页面来更改行为。您需要在src/main/resources/public/error/位置创建自定义HTML页面,以便创建500.html或404.html页面。如果要创建RESTful应用程序,SpringBoot将以JSON格式响应。当您使用@ContorllerAdvice或@ExceptionHandler注释时,SpringBoot还支持SpringMVC来处理错误。您可以通过实现ErrorPageRegistrar并将其声明为Springbean来注册自定义ErrorPages。•模板引擎支持。SpringBoot支持FreeMarker,Groovy模板,Thymeleaf和Mustache。当您包含spring-¬boot-starter-<templateengine>依赖项时,需要SpringBoot自动配置来启用和添加所有必需的视图解析器和文件处理程序。默认情况下,SpringBoot会查看src/main/resources/template/路径。SpringBootWeb自动配置还提供了许多其他功能。现在,只关注Servlet技术,但很快就进入了SpringBoot系列的最新成员:WebFlux。SpringBootWeb:创建App为了更好地理解SpringBoot如何与Web应用程序一起工作以及SpringMVC模块的强大功能,您将创建一个暴露RESTfulAPI的ToDo应用程序。这些是要求:•创建具有以下字段和类型的ToDo域模型:id(字符串),description(字符串),completed(布尔),创建(日期与时间),修改(日期与时间)。•创建RESTfulAPI,提供基本的CRUD(创建,读取,更新,删除)操作。使用最常见的HTTP方法:POST,PUT,PATCH,GET和DELETE。•创建一个处理多个ToDo状态的存储库。目前,内存存储库就足够了。•在有错误请求或提交新ToDo时没有必填字段时添加错误处理程序。唯一的必填字段是描述。•所有请求和响应都应采用JSON格式。•Group:com.apress.todo•Artifact:todo-in-memory•Name:todo-in-memory•PackageName:com.apress.todo•Dependencies:Web,Lombok选择Lombok依赖项有助于轻松创建域模型类,并消除样板设置器,getter和其他覆盖。您可以选择Maven或Gradle作为项目类型;按GenerateProject按钮并下载ZIP文件。解压缩并将其导入您喜欢的IDE。一些最好的IDE是STS,IntelliJIDEA和VSCode我推荐其中一个IDE用于代码完成功能,它可以帮助您查看要添加到代码中的方法或参数。DomainModel:域模型根据需求,您需要创建ToDo域模型类显示ToDo类,其中包含所有必填字段。它还使用@Data注释,这是一个Lombok注释,它生成一个默认构造函数(如果没有),以及所有setter,getter和覆盖(如toString方法),以使类更清晰。另请注意,该类在某些字段中包含@NotNull和@NotBlank注释;这些注释用于我们稍后进行的验证。默认构造函数具有字段初始化,因此很容易创建ToDo实例。FluentAPI:生成器接下来让我们创建一个帮助创建ToDo实例的FluentAPI类。您可以在此类中看到创建带有描述或具有特定ID的ToDo的工厂。存储库:CommonRepository<T>是用于创建一个具有公共持久性操作的接口。此接口是通用的,因此很容易使用任何其他实现,使repo成为可扩展的解决方案。有一个通用接口可以用作任何其他持久性实现的基础。当然,您可以随时更改这些签名。这只是关于如何创建可扩展内容的示例。ToDoRepository:存储库创建一个实现CommonRepository<T>接口的具体类。记住规范;目前,只需让内存中的ToDo显示CommonRepository<T>接口的实现。查看代码并进行分析。这个类使用的是一个包含所有ToDo的哈希。所有操作都简化了哈希的性质,使其易于实现。ToDoValidationErrorBuilder:验证接下来,让我们创建一个验证类,公开应用程序中的任何可能的错误,例如没有描述的ToDo。请记住,在ToDo类中,ID和description字段标记为@NotNull。description字段有一个额外的@NotBlank注释,以确保它永远是空的,显示ToDoValidationError类,它保存任何请求产生的任何错误。它使用一个额外的@JsonInclude注释,它表示即使errors字段为空,也必须包含它。Controller:创建控制器现在,是时候创建RESTfulAPI并使用之前的所有类。您可以创建ToDoController类,在其中可以看到所有SpringMVC功能,注释,配置端点的方式以及如何处理错误。•@RestController。SpringMVC提供@Controller和@RestController来表达请求映射,请求输入,异常处理等。所有功能都依赖于这些注释,因此无需扩展或实现特定于接口的接口。•@RequestMapping。此批注将请求映射到控制器方法。有几个属性可以匹配URL,HTTP方法(GET,PUT,DELETE等),请求参数,标头和媒体类型。它可以在类级别(共享映射)或在特定端点映射的方法级别使用。在这种情况下,它标有“/api”,表示所有方法都有此前缀。•@Autowired。构造函数使用@Autowired注释,这意味着它注入了CommonRepository<ToDo>实现。该注释可以省略;从版本4.3开始,Spring会自动注入任何声明的依赖项。•@GetMapping。这是@RequestMapping批注的快捷变体,对HTTPGET方法很有用。@GetMapping相当于@RequestMapping(value=“/todo”,method={RequestMethod.GET})。•@PatchMapping。这是@RequestMapping注释的快捷方式变体;在这个类中,它标记为ToDo已完成。•@DeleteMapping。这是@RequestMapping注释的快捷方式变体;它用于删除ToDo。有两种重载方法:deleteToDo,一个接受String,另一个接收ToDo实例。•@PathVariable。当您声明包含URL表达式模式的端点时,此批注很有用;在这种情况下,“/api/todo/{id}”,其中ID必须与方法参数的名称匹配。•@RequestBody。此批注向主体发送请求。通常,当您提交表单或特定内容时,此类接收JSON格式ToDo,然后HttpMessageConverter将JSON反序列化为ToDo实例;这是由SpringBoot及其自动配置自动完成的,因为它默认注册MappingJackson2HttpMessageConverter。•ResponseEntity<T>。此类返回完整响应,包括HTTP标头,并通过HttpMessageConverters转换主体并将其写入HTTP响应。ResponseEntity<T>类支持流畅的API,因此很容易创建响应。•@ResponseStatus。通常,当方法具有void返回类型(或null返回值)时,
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 《组织绩效诊断》课件
- 《利玛窦在肇庆》课件
- 广东碧桂园职业学院《大学体育II》2023-2024学年第一学期期末试卷
- 《百日咳患者的护理》课件
- 赣西科技职业学院《食品卫生学》2023-2024学年第一学期期末试卷
- 《核物理基础》课件
- 七年级语文上册第五单元写作如何突出中心新人教版
- 三年级品德与社会下册第四单元第四课马路不是游戏场教案新人教版
- 三年级科学上册第四单元人与水10用水量的调查教案首师大版
- 《货好不用广告》课件
- 统编版(2024新版)七年级上册道德与法治期末综合测试卷(含答案)
- 文化创意合作战略协议
- 国家开放大学法学本科《商法》历年期末考试试题及答案题库
- 安全管理人员安全培训教材
- 2024年妇保科工作总结及计划
- 北京理工大学《数据结构与算法设计》2022-2023学年第一学期期末试卷
- 锚杆(索)支护工技能理论考试题库200题(含答案)
- 影视后期制作团队薪酬激励方案
- 2024年有限合伙股权代持
- 广东珠海市驾车冲撞行人案件安全防范专题培训
- 花城版一年级上册音乐 第3课 《国旗国旗真美丽》(教案)
评论
0/150
提交评论