毕业设计外文文献—Spring Boot的Web应用程序.docx

上传人:zf 文档编号:30801481 上传时间:2023-11-22 格式:DOCX 页数:26 大小:31.13KB
下载 相关 举报
毕业设计外文文献—Spring Boot的Web应用程序.docx_第1页
第1页 / 共26页
毕业设计外文文献—Spring Boot的Web应用程序.docx_第2页
第2页 / 共26页
毕业设计外文文献—Spring Boot的Web应用程序.docx_第3页
第3页 / 共26页
毕业设计外文文献—Spring Boot的Web应用程序.docx_第4页
第4页 / 共26页
毕业设计外文文献—Spring Boot的Web应用程序.docx_第5页
第5页 / 共26页
点击查看更多>>
下载资源
资源描述

毕业设计外文文献—Spring Boot的Web应用程序.docx

《毕业设计外文文献—Spring Boot的Web应用程序.docx》由会员分享,可在线阅读,更多相关《毕业设计外文文献—Spring Boot的Web应用程序.docx(26页珍藏版)》请在冰豆网上搜索。

毕业设计外文文献—Spring Boot的Web应用程序.docx

附录A外文翻译—原文部分

F.Gutierrez,ProSpringBoot2

WebApplicationswithSpringBoot

Nowadays,thewebisthemainchannelforanytypeofapplication—fromdesktoptomobiledevices,fromsocialandbusinessapplicationstogames,andfromsimplecontenttostreamingdata.Withthisismind,SpringBootcanhelpyoueasilydevelopthenextgenerationofwebapplications.

ThischaptershowsyouhowtocreateSpringBootwebapplicationswithease.Youhavealreadylearned,withsomeexamplesinearlierchapters,whatyoucandowiththeweb.YoulearnedthatSpringBootmakesiteasiertocreatewebappswithafewlinesofcodeandthatyoudon’tneedtoworryaboutconfigurationfilesorlookforanapplicationservertodeployyourwebapplication.ByusingSpringBootanditsauto-configuration,youcanhaveanembeddedapplicationserver,suchasTomcat,Nettie,Undertow,orJetty,whichmakesyourappverydistributableandportable.

SpringMVC

Let’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-Configuration

Webapplicationscanbecreatedeasilybyaddingthespring-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/todoformat=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:

ToDoApp

TobetterunderstandhowSpringBootworkswithwebapplicationsandthepoweroftheSpringMVCmodules,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.

ToDoApp

Openyourbrowserandgotohttps:

//start.spring.iotocreateyourToDoappbyusingthefollowingvalues.

Group:

com.apress.todo

Artifact:

todo-in-memory

Name:

todo-in-memory

PackageName:

com.apress.todo

Dependencies:

Web,Lombok

ChoosingtheLombokdependencyhelpseasilycreatethedomainmodelclassesandeliminatestheboilerplatesetters,getters,andotheroverrides.

YoucanselecteitherMavenorGradleastheprojecttype;inthisbook,weusebothindistinctly.PresstheGenerateProjectbuttonanddownloadtheZIPfile.UncompressitandimportitintoyourfavoriteIDE.SomeofthebestIDEsareSTS(https:

//spring.io/tools/sts/all),IntelliJIDEA(/idea/),andVSCod(/).IrecommendoneoftheseIDEsforthecodecompletionfeature,whichhelpsyouseethemethodsorparameterstoaddtoyourcode.

DomainModel:

ToDo

Basedontherequirements,youneedtocreateaToDodomainmodelclass.

showsyoutheToDoclass,whichhasalltherequiredfields.Italsousesthe@Dataannotation,whichisaLombokannotationthatgeneratesadefaultconstructor(ifyoudon’thaveone)andallthesetters,getters,andoverrides,suchasthetoStringmethod,tomaketheclasscleaner.Alsonotethattheclasshasthe@NotNulland@NotBlankannotationsinsomeofthefields;theseannotationsareusedinthevalidationthatwedolateron.Thedefaultconstructorhasfieldinitialization,soitiseasytocreateaToDoinstance.

FluentAPI:

ToDoBuilder

Nextlet’screateaFluentAPIclassthathelpscreateaToDoinstance.YoucanseethisclassafactorythatcreatesaToDowithadescriptionorwithaparticularID.

Repository:

CommonRepository<T>.Next,c

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > PPT模板 > 艺术创意

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1