




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
附錄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應(yīng)用程序如今,網(wǎng)絡(luò)是任何類型應(yīng)用程序的主要渠道,從桌面到移動(dòng)設(shè)備,從社交和商業(yè)應(yīng)用程序到游戲,從簡(jiǎn)單內(nèi)容到流數(shù)據(jù)。有了這個(gè)想法,SpringBoot可以幫助您輕松開發(fā)下一代Web應(yīng)用程序。本文將介紹如何輕松創(chuàng)建SpringBootWeb應(yīng)用程序。已經(jīng)通過(guò)前面一些示例了解了可以使用Web做什么。了解到SpringBoot可以更輕松地使用幾行代碼創(chuàng)建Web應(yīng)用程序,并且無(wú)需擔(dān)心配置文件或?qū)ふ覒?yīng)用程序服務(wù)器來(lái)部署Web應(yīng)用程序。通過(guò)使用SpringBoot及其自動(dòng)配置,可以擁有一個(gè)嵌入式應(yīng)用程序服務(wù)器,如Tomcat,Nettie,Undertow或Jetty,這使得應(yīng)用程序可以非常易于分發(fā)和移植。SpringMVC現(xiàn)在開始討論SpringMVC技術(shù)及其一些功能。請(qǐng)記住,SpringFramework包含大約20個(gè)模塊或技術(shù),Web技術(shù)就是其中之一。對(duì)于Web技術(shù),SpringFramework具有spring-web,spring-webmvc,spring-webflux和spring-websocket模塊。spring-web模塊具有基本的Web集成功能,例如多部分文件上載功能,Spring容器的初始化(通過(guò)使用servlet偵聽器)和面向Web的應(yīng)用程序上下文。spring-mvc模塊(也就是Web服務(wù)器模塊)包含Web應(yīng)用程序的所有SpringMVC(模型-視圖-控制器)和REST服務(wù)實(shí)現(xiàn)。這些模塊提供了許多功能,例如非常強(qiáng)大的JSP標(biāo)記庫(kù),可自定義的綁定和驗(yàn)證,靈活的模型傳輸,可自定義的處理程序和視圖分辨率等。SpringMVC是圍繞org.springframework.web.servlet設(shè)計(jì)的。DispatcherServlet類。這個(gè)servlet非常靈活,并且具有非常強(qiáng)大的功能,在任何其他MVCWeb框架中都找不到。使用DispatcherServlet,您可以使用多種開箱即用的解析策略,包括視圖解析器,區(qū)域設(shè)置解析器,主題解析器和異常處理程序。換句話說(shuō),DispatcherServlet接受HTTP請(qǐng)求并將其重定向到正確的處理程序(標(biāo)記為@Controller或@RestController的類以及使用@RequestMapping注釋的方法)。SpringBootMVC自動(dòng)配置通過(guò)將spring-boot-starter-web依賴項(xiàng)添加到pom.xml或build.gradle文件,可以輕松創(chuàng)建Web應(yīng)用程序。這種依賴提供了所有必需的spring-webjar和一些額外的jar,例如tomcat-embed*和jackson(用于JSON和XML)。這意味著SpringBoot使用SpringMVC模塊的強(qiáng)大功能,并提供所有必要的自動(dòng)配置,以創(chuàng)建正確的Web基礎(chǔ)結(jié)構(gòu),例如配置DispatcherServlet,提供默認(rèn)值(除非您覆蓋它),設(shè)置嵌入式Tomcat服務(wù)器(所以你可以在沒(méi)有任何應(yīng)用程序容器的情況下運(yùn)行應(yīng)用程序)等等。自動(dòng)配置會(huì)將以下功能添加到Web應(yīng)用程序中:?靜態(tài)內(nèi)容支持。這意味著您可以添加靜態(tài)內(nèi)容,如導(dǎo)演中的HTML,JavaScript,CSS,媒體等等named/static(默認(rèn)情況下)或/public,/resources或/META-INF/資源,應(yīng)該在您的類路徑或當(dāng)前directory.SpringBoot選擇它并根據(jù)請(qǐng)求提供它們。你可以通過(guò)修改spring.mvc.static-path-來(lái)輕松改變這一點(diǎn)pattern或spring.resources.static-locations屬性。SpringBoot和Web應(yīng)用程序的一個(gè)很酷的功能如果你創(chuàng)建一個(gè)index.html文件,SpringBoot會(huì)為它提供服務(wù)自動(dòng)無(wú)需注冊(cè)任何其他bean或需要額外的組態(tài)。?Http消息轉(zhuǎn)換器。如果您使用常規(guī)的SpringMVC應(yīng)用程序,您需要獲得ISON響應(yīng)。創(chuàng)建必要的配置(XML或JavaConfig)將Http消息轉(zhuǎn)換成bean,SpringBoot默認(rèn)添加此支持,因此您不必這樣做;這意味著您默認(rèn)獲得JSON格式(由于spring-boot-starter-web提供的Jackson庫(kù)作為依賴項(xiàng))。如果SpringBoot自動(dòng)配置發(fā)現(xiàn)您在類路徑中有JacksonXML擴(kuò)展,它會(huì)將XMLHttpMessageConverter聚合到轉(zhuǎn)換器,這意味著您的應(yīng)用程序可以根據(jù)您的內(nèi)容類型請(qǐng)求(application/json或application/xml)進(jìn)行服務(wù)。?JSON序列化程序和反序列化程序。如果你想對(duì)JSON的序列化/反序列化有更多的控制,SpringBoot提供了一種簡(jiǎn)單的方法來(lái)創(chuàng)建你自己的,通過(guò)從JsonSerializer<T>和JsonDeserializer<T>擴(kuò)展,并使用@JsonComponent注釋你的類,以便它可以注冊(cè)用法。SpringBoot的另一個(gè)特色是杰克遜的支持;默認(rèn)情況下,SpringBoot將日期字段序列化為2018-05-01T23:31:38.141+0000,但您可以通過(guò)更改spring.jackson.date-format=yyyy-MM-dd屬性來(lái)更改此默認(rèn)行為(您可以應(yīng)用任何日期格式圖案);上一個(gè)值生成輸出,例如2018-05-01。?路徑匹配和內(nèi)容協(xié)商。SpringMVC應(yīng)用程序?qū)嵺`之一是能夠響應(yīng)任何后綴以表示內(nèi)容類型響應(yīng)及其內(nèi)容協(xié)商。如果您有/api/todo.json或/api/todo.pdf之類的內(nèi)容,則將content-type設(shè)置為application/json和application/pdf;所以響應(yīng)分別是JSON格式或PDF文件。換句話說(shuō),SpringMVC執(zhí)行.*后綴模式匹配,例如/api/todo.*.SpringBoot默認(rèn)禁用此功能。您仍然可以使用spring.mvc.contentnegotiation.favor-parameter=true屬性添加參數(shù)的功能(默認(rèn)為false);所以你可以做/api/todo?format=xml。(format是默認(rèn)參數(shù)名稱;當(dāng)然,您可以使用spring.mvc.contentnegotiation.parameter-name=myparam更改它。這會(huì)觸發(fā)content-type到application/xml。?錯(cuò)誤處理。SpringBoot使用/error映射創(chuàng)建一個(gè)白色標(biāo)記頁(yè)面以顯示所有全局錯(cuò)誤。您可以通過(guò)創(chuàng)建自己的自定義頁(yè)面來(lái)更改行為。您需要在src/main/resources/public/error/位置創(chuàng)建自定義HTML頁(yè)面,以便創(chuàng)建500.html或404.html頁(yè)面。如果要?jiǎng)?chuàng)建RESTful應(yīng)用程序,SpringBoot將以JSON格式響應(yīng)。當(dāng)您使用@ContorllerAdvice或@ExceptionHandler注釋時(shí),SpringBoot還支持SpringMVC來(lái)處理錯(cuò)誤。您可以通過(guò)實(shí)現(xiàn)ErrorPageRegistrar并將其聲明為Springbean來(lái)注冊(cè)自定義ErrorPages。?模板引擎支持。SpringBoot支持FreeMarker,Groovy模板,Thymeleaf和Mustache。當(dāng)您包含spring-?boot-starter-<templateengine>依賴項(xiàng)時(shí),需要SpringBoot自動(dòng)配置來(lái)啟用和添加所有必需的視圖解析器和文件處理程序。默認(rèn)情況下,SpringBoot會(huì)查看src/main/resources/template/路徑。SpringBootWeb自動(dòng)配置還提供了許多其他功能?,F(xiàn)在,只關(guān)注Servlet技術(shù),但很快就進(jìn)入了SpringBoot系列的最新成員:WebFlux。SpringBootWeb:創(chuàng)建App為了更好地理解SpringBoot如何與Web應(yīng)用程序一起工作以及SpringMVC模塊的強(qiáng)大功能,您將創(chuàng)建一個(gè)暴露RESTfulAPI的ToDo應(yīng)用程序。這些是要求:?創(chuàng)建具有以下字段和類型的ToDo域模型:id(字符串),description(字符串),completed(布爾),創(chuàng)建(日期與時(shí)間),修改(日期與時(shí)間)。?創(chuàng)建RESTfulAPI,提供基本的CRUD(創(chuàng)建,讀取,更新,刪除)操作。使用最常見的HTTP方法:POST,PUT,PATCH,GET和DELETE。?創(chuàng)建一個(gè)處理多個(gè)ToDo狀態(tài)的存儲(chǔ)庫(kù)。目前,內(nèi)存存儲(chǔ)庫(kù)就足夠了。?在有錯(cuò)誤請(qǐng)求或提交新ToDo時(shí)沒(méi)有必填字段時(shí)添加錯(cuò)誤處理程序。唯一的必填字段是描述。?所有請(qǐng)求和響應(yīng)都應(yīng)采用JSON格式。?Group:com.apress.todo?Artifact:todo-in-memory?Name:todo-in-memory?PackageName:com.apress.todo?Dependencies:Web,Lombok選擇Lombok依賴項(xiàng)有助于輕松創(chuàng)建域模型類,并消除樣板設(shè)置器,getter和其他覆蓋。您可以選擇Maven或Gradle作為項(xiàng)目類型;按GenerateProject按鈕并下載ZIP文件。解壓縮并將其導(dǎo)入您喜歡的IDE。一些最好的IDE是STS,IntelliJIDEA和VSCode我推薦其中一個(gè)IDE用于代碼完成功能,它可以幫助您查看要添加到代碼中的方法或參數(shù)。DomainModel:域模型根據(jù)需求,您需要?jiǎng)?chuàng)建ToDo域模型類顯示ToDo類,其中包含所有必填字段。它還使用@Data注釋,這是一個(gè)Lombok注釋,它生成一個(gè)默認(rèn)構(gòu)造函數(shù)(如果沒(méi)有),以及所有setter,getter和覆蓋(如toString方法),以使類更清晰。另請(qǐng)注意,該類在某些字段中包含@NotNull和@NotBlank注釋;這些注釋用于我們稍后進(jìn)行的驗(yàn)證。默認(rèn)構(gòu)造函數(shù)具有字段初始化,因此很容易創(chuàng)建ToDo實(shí)例。FluentAPI:生成器接下來(lái)讓我們創(chuàng)建一個(gè)幫助創(chuàng)建ToDo實(shí)例的FluentAPI類。您可以在此類中看到創(chuàng)建帶有描述或具有特定ID的ToDo的工廠。存儲(chǔ)庫(kù):CommonRepository<T>是用于創(chuàng)建一個(gè)具有公共持久性操作的接口。此接口是通用的,因此很容易使用任何其他實(shí)現(xiàn),使repo成為可擴(kuò)展的解決方案。有一個(gè)通用接口可以用作任何其他持久性實(shí)現(xiàn)的基礎(chǔ)。當(dāng)然,您可以隨時(shí)更改這些簽名。這只是關(guān)于如何創(chuàng)建可擴(kuò)展內(nèi)容的示例。ToDoRepository:存儲(chǔ)庫(kù)創(chuàng)建一個(gè)實(shí)現(xiàn)CommonRepository<T>接口的具體類。記住規(guī)范;目前,只需讓內(nèi)存中的ToDo顯示CommonRepository<T>接口的實(shí)現(xiàn)。查看代碼并進(jìn)行分析。這個(gè)類使用的是一個(gè)包含所有ToDo的哈希。所有操作都簡(jiǎn)化了哈希的性質(zhì),使其易于實(shí)現(xiàn)。ToDoValidationErrorBuilder:驗(yàn)證接下來(lái),讓我們創(chuàng)建一個(gè)驗(yàn)證類,公開應(yīng)用程序中的任何可能的錯(cuò)誤,例如沒(méi)有描述的ToDo。請(qǐng)記住,在ToDo類中,ID和description字段標(biāo)記為@NotNull。description字段有一個(gè)額外的@NotBlank注釋,以確保它永遠(yuǎn)是空的,顯示ToDoValidationError類,它保存任何請(qǐng)求產(chǎn)生的任何錯(cuò)誤。它使用一個(gè)額外的@JsonInclude注釋,它表示即使errors字段為空,也必須包含它。Controller:創(chuàng)建控制器現(xiàn)在,是時(shí)候創(chuàng)建RESTfulAPI并使用之前的所有類。您可以創(chuàng)建ToDoController類,在其中可以看到所有SpringMVC功能,注釋,配置端點(diǎn)的方式以及如何處理錯(cuò)誤。?@RestController。SpringMVC提供@Controller和@RestController來(lái)表達(dá)請(qǐng)求映射,請(qǐng)求輸入,異常處理等。所有功能都依賴于這些注釋,因此無(wú)需擴(kuò)展或?qū)崿F(xiàn)特定于接口的接口。?@RequestMapping。此批注將請(qǐng)求映射到控制器方法。有幾個(gè)屬性可以匹配URL,HTTP方法(GET,PUT,DELETE等),請(qǐng)求參數(shù),標(biāo)頭和媒體類型。它可以在類級(jí)別(共享映射)或在特定端點(diǎn)映射的方法級(jí)別使用。在這種情況下,它標(biāo)有“/api”,表示所有方法都有此前綴。?@Autowired。構(gòu)造函數(shù)使用@Autowired注釋,這意味著它注入了CommonRepository<ToDo>實(shí)現(xiàn)。該注釋可以省略;從版本4.3開始,Spring會(huì)自動(dòng)注入任何聲明的依賴項(xiàng)。?@GetMapping。這是@RequestMapping批注的快捷變體,對(duì)HTTPGET方法很有用。@GetMapping相當(dāng)于@RequestMapping(value=“/todo”,method={RequestMethod.GET})。?@PatchMapping。這是@RequestMapping注釋的快捷方式變體;在這個(gè)類中,它標(biāo)記為ToDo已完成。?@DeleteMapping。這是@RequestMapping注釋的快捷方式變體;它用于刪除ToDo。有兩種重載方法:deleteToDo,一個(gè)接受String,另一個(gè)接收ToDo實(shí)例。?@PathVariable。當(dāng)您聲明包含URL表達(dá)式模式的端點(diǎn)時(shí),此批注很有用;在這種情況下,“/api/todo/{id}”,其中ID必須與方法參數(shù)的名稱匹配。?@RequestBody。此批注向主體發(fā)送請(qǐng)求。通常,當(dāng)您提交表單或特定內(nèi)容時(shí),此類接收J(rèn)SON格式ToDo,然后HttpMessageConverter將JSON反序列化為ToDo實(shí)例;這是由SpringBoot及其自動(dòng)配置自動(dòng)完成的,因?yàn)樗J(rèn)注冊(cè)MappingJackson2HttpMessageConverter。?ResponseEntity<T>。此類返回完整響應(yīng),包括HTTP標(biāo)頭,并通過(guò)HttpMessageConverters轉(zhuǎn)換主體并將其寫入HTTP響應(yīng)。ResponseEntity<T>類支持流暢的API,因此很容易創(chuàng)建響應(yīng)。?@ResponseStatus。通常,當(dāng)方法具有void返回類型(或null返回值)時(shí),
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 大五人格與教育政策執(zhí)行力的關(guān)系研究
- 智慧城市防災(zāi)減災(zāi)教育領(lǐng)域的創(chuàng)新與實(shí)踐
- 智慧城市安全防護(hù)新篇章視頻監(jiān)控與大數(shù)據(jù)的融合應(yīng)用
- 教育機(jī)器人在職業(yè)培訓(xùn)中的應(yīng)用和價(jià)值分析
- 教育數(shù)據(jù)分析提升課程設(shè)計(jì)的有效途徑
- 技術(shù)在商業(yè)競(jìng)爭(zhēng)中的關(guān)鍵作用
- 醫(yī)療創(chuàng)新重塑健康管理與醫(yī)療服務(wù)
- 抖音商戶直播價(jià)格策略審批登記制度
- 公交優(yōu)先策略對(duì)2025年城市交通擁堵治理的影響分析報(bào)告
- 公眾參與視角下環(huán)境影響評(píng)價(jià)信息公開策略研究報(bào)告
- T/CCOA 50-2023低菌小麥粉生產(chǎn)技術(shù)規(guī)程
- 安全生產(chǎn)責(zé)任制度完整版
- 2025屆遼寧省大連市高新園區(qū)七年級(jí)數(shù)學(xué)第二學(xué)期期末考試試題含解析
- 2025+NCCN非小細(xì)胞肺癌診療指南解讀
- ECMO治療暴發(fā)性心肌炎
- 2025CSCO乳腺癌診療指南解讀課件
- 社會(huì)單位消防安全評(píng)估導(dǎo)則
- 衛(wèi)生系列高級(jí)職稱申報(bào)工作量統(tǒng)計(jì)表(醫(yī)療類)
- 寵物店聘用合同協(xié)議
- 食堂外人出入管理制度
- 大數(shù)據(jù)驅(qū)動(dòng)設(shè)備優(yōu)化設(shè)計(jì)-全面剖析
評(píng)論
0/150
提交評(píng)論