




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
畢業(yè)設計(論文)外文資料翻譯外文出處:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html附件:A.外文翻譯-原文部分B.外文翻譯-譯文部分
附錄A.外文翻譯-原文部分FROM:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.htmlSpringWebMVCSpringWebMVCistheoriginalwebframeworkbuiltontheServletAPIandhasbeenincludedintheSpringFrameworkfromtheverybeginning.Theformalname,“SpringWebMVC,”comesfromthenameofitssourcemodule(spring-webmvc),butitismorecommonlyknownas“SpringMVC”.1.1.DispatcherServletSameasinSpringWebFluxSpringMVC,asmanyotherwebframeworks,isdesignedaroundthefrontcontrollerpatternwhereacentral
Servlet,the
DispatcherServlet,providesasharedalgorithmforrequestprocessing,whileactualworkisperformedbyconfigurabledelegatecomponents.Thismodelisflexibleandsupportsdiverseworkflows.The
DispatcherServlet,asany
Servlet,needstobedeclaredandmappedaccordingtotheServletspecificationbyusingJavaconfigurationorin
web.xml.Inturn,the
DispatcherServlet
usesSpringconfigurationtodiscoverthedelegatecomponentsitneedsforrequestmapping,viewresolution,exceptionhandling,
andmore.ThefollowingexampleoftheJavaconfigurationregistersandinitializesthe
DispatcherServlet,whichisauto-detectedbytheServletcontainer(see
ServletConfig):publicclassMyWebApplicationInitializerimplementsWebApplicationInitializer{@OverridepublicvoidonStartup(ServletContextservletCxt){//LoadSpringwebapplicationconfigurationAnnotationConfigWebApplicationContextac=newAnnotationConfigWebApplicationContext();ac.register(AppConfig.class);ac.refresh();//CreateandregistertheDispatcherServletDispatcherServletservlet=newDispatcherServlet(ac);ServletRegistration.Dynamicregistration=servletCxt.addServlet("app",servlet);registration.setLoadOnStartup(1);registration.addMapping("/app/*");}}InadditiontousingtheServletContextAPIdirectly,youcanalsoextendAbstractAnnotationConfigDispatcherServletInitializer
andoverridespecificmethods(seetheexampleunder
ContextHierarchy).Thefollowingexampleof
web.xml
configurationregistersandinitializesthe
DispatcherServlet:<web-app><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/app-context.xml</param-value></context-param><servlet><servlet-name>app</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value></param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>app</servlet-name><url-pattern>/app/*</url-pattern></servlet-mapping></web-app>SpringBootfollowsadifferentinitializationsequence.RatherthanhookingintothelifecycleoftheServletcontainer,SpringBootusesSpringconfigurationtobootstrapitselfandtheembeddedServletcontainer.
Filter
and
Servlet
declarationsaredetectedinSpringconfigurationandregisteredwiththeServletcontainer.Formoredetails,seethe
SpringBootdocumentation.1.1.1.ContextHierarchyDispatcherServlet
expectsa
WebApplicationContext
(anextensionofaplain
ApplicationContext)foritsownconfiguration.
WebApplicationContext
hasalinktothe
ServletContext
andthe
Servlet
withwhichitisassociated.Itisalsoboundtothe
ServletContext
suchthatapplicationscanusestaticmethodson
RequestContextUtils
tolookupthe
WebApplicationContextiftheyneedaccesstoit.Formanyapplications,havingasingle
WebApplicationContext
issimpleandsuffices.Itisalsopossibletohaveacontexthierarchywhereoneroot
WebApplicationContext
issharedacrossmultiple
DispatcherServlet
(orother
Servlet)instances,eachwithitsownchild
WebApplicationContext
configuration.See
AdditionalCapabilitiesofthe?ApplicationContext
formoreonthecontexthierarchyfeature.Theroot
WebApplicationContext
typicallycontainsinfrastructurebeans,suchasdatarepositoriesandbusinessservicesthatneedtobesharedacrossmultiple
Servlet
instances.Thosebeansareeffectivelyinheritedandcanbeoverridden(thatis,re-declared)intheServlet-specificchild
WebApplicationContext,whichtypicallycontainsbeanslocaltothegiven
Servlet.Thefollowingimageshowsthisrelationship:Thefollowingexampleconfiguresa
WebApplicationContext
hierarchy:publicclassMyWebAppInitializerextendsAbstractAnnotationConfigDispatcherServletInitializer{@OverrideprotectedClass<?>[]getRootConfigClasses(){returnnewClass<?>[]{RootConfig.class};}@OverrideprotectedClass<?>[]getServletConfigClasses(){returnnewClass<?>[]{App1Config.class};}@OverrideprotectedString[]getServletMappings(){returnnewString[]{"/app1/*"};}}Ifanapplicationcontexthierarchyisnotrequired,applicationscanreturnallconfigurationthrough
getRootConfigClasses()
and
null
from
getServletConfigClasses().Thefollowingexampleshowsthe
web.xml
equivalent:<web-app><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/root-context.xml</param-value></context-param><servlet><servlet-name>app1</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/app1-context.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>app1</servlet-name><url-pattern>/app1/*</url-pattern></servlet-mapping></web-app>Ifanapplicationcontexthierarchyisnotrequired,applicationsmayconfigurea“root”contextonlyandleavethe
contextConfigLocation
Servletparameterempty.1.1.2.SpecialBeanTypesSameasinSpringWebFluxThe
DispatcherServlet
delegatestospecialbeanstoprocessrequestsandrendertheappropriateresponses.By“specialbeans”wemeanSpring-managed
Object
instancesthatimplementframeworkcontracts.Thoseusuallycomewithbuilt-incontracts,butyoucancustomizetheirpropertiesandextendorreplacethem.Thefollowingtableliststhespecialbeansdetectedbythe
DispatcherServlet:BeantypeExplanationHandlerMappingMaparequesttoahandleralongwithalistof
interceptors
forpre-andpost-processing.Themappingisbasedonsomecriteria,thedetailsofwhichvaryby
HandlerMapping
implementation.Thetwomain
HandlerMapping
implementationsare
RequestMappingHandlerMapping
(whichsupports
@RequestMapping
annotatedmethods)and
SimpleUrlHandlerMapping
(whichmaintainsexplicitregistrationsofURIpathpatternstohandlers).HandlerAdapterHelpthe
DispatcherServlet
toinvokeahandlermappedtoarequest,regardlessofhowthehandlerisactuallyinvoked.Forexample,invokinganannotatedcontrollerrequiresresolvingannotations.Themainpurposeofa
HandlerAdapteristoshieldthe
DispatcherServlet
fromsuchdetails.HandlerExceptionResolverStrategytoresolveexceptions,possiblymappingthemtohandlers,toHTMLerrorviews,orothertargets.See
Exceptions.ViewResolverResolvelogical
String-basedviewnamesreturnedfromahandlertoanactual
View
withwhichtorendertotheresponse.See
ViewResolution
and
ViewTechnologies.LocaleResolver,
LocaleContextResolverResolvethe
Locale
aclientisusingandpossiblytheirtimezone,inordertobeabletoofferinternationalizedviews.See
Locale.ThemeResolverResolvethemesyourwebapplicationcanuse?—?forexample,toofferpersonalizedlayouts.See
Themes.MultipartResolverAbstractionforparsingamulti-partrequest(forexample,browserformfileupload)withthehelpofsomemultipartparsinglibrary.See
MultipartResolver.FlashMapManagerStoreandretrievethe“input”andthe“output”
FlashMap
thatcanbeusedtopassattributesfromonerequesttoanother,usuallyacrossaredirect.See
FlashAttributes.1.1.3.WebMVCConfigSameasinSpringWebFluxApplicationscandeclaretheinfrastructurebeanslistedin
SpecialBeanTypes
thatarerequiredtoprocessrequests.The
DispatcherServlet
checksthe
WebApplicationContext
foreachspecialbean.Iftherearenomatchingbeantypes,itfallsbackonthedefaulttypeslistedin
DispatcherSperties.Inmostcases,the
MVCConfig
isthebeststartingpoint.ItdeclarestherequiredbeansineitherJavaorXMLandprovidesahigher-levelconfigurationcallbackAPItocustomizeit.SpringBootreliesontheMVCJavaconfigurationtoconfigureSpringMVCandprovidesmanyextraconvenientoptions.1.1.4.ServletConfigInaServlet3.0+environment,youhavetheoptionofconfiguringtheServletcontainerprogrammaticallyasanalternativeorincombinationwitha
web.xml
file.Thefollowingexampleregistersa
DispatcherServlet:importorg.springframework.web.WebApplicationInitializer;publicclassMyWebApplicationInitializerimplementsWebApplicationInitializer{@OverridepublicvoidonStartup(ServletContextcontainer){XmlWebApplicationContextappContext=newXmlWebApplicationContext();appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");ServletRegistration.Dynamicregistration=container.addServlet("dispatcher",newDispatcherServlet(appContext));registration.setLoadOnStartup(1);registration.addMapping("/");}}WebApplicationInitializer
isaninterfaceprovidedbySpringMVCthatensuresyourimplementationisdetectedandautomaticallyusedtoinitializeanyServlet3container.Anabstractbaseclassimplementationof
WebApplicationInitializernamed
AbstractDispatcherServletInitializer
makesiteveneasiertoregisterthe
DispatcherServlet
byoverridingmethodstospecifytheservletmappingandthelocationofthe
DispatcherServlet
configuration.ThisisrecommendedforapplicationsthatuseJava-basedSpringconfiguration,asthefollowingexampleshows:publicclassMyWebAppInitializerextendsAbstractAnnotationConfigDispatcherServletInitializer{@OverrideprotectedClass<?>[]getRootConfigClasses(){returnnull;}@OverrideprotectedClass<?>[]getServletConfigClasses(){returnnewClass<?>[]{MyWebConfig.class};}@OverrideprotectedString[]getServletMappings(){returnnewString[]{"/"};}}IfyouuseXML-basedSpringconfiguration,youshouldextenddirectlyfrom
AbstractDispatcherServletInitializer,asthefollowingexampleshows:publicclassMyWebAppInitializerextendsAbstractDispatcherServletInitializer{@OverrideprotectedWebApplicationContextcreateRootApplicationContext(){returnnull;}@OverrideprotectedWebApplicationContextcreateServletApplicationContext(){XmlWebApplicationContextcxt=newXmlWebApplicationContext();cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");returncxt;}@OverrideprotectedString[]getServletMappings(){returnnewString[]{"/"};}}AbstractDispatcherServletInitializer
alsoprovidesaconvenientwaytoadd
Filter
instancesandhavethembeautomaticallymappedtothe
DispatcherServlet,asthefollowingexampleshows:publicclassMyWebAppInitializerextendsAbstractDispatcherServletInitializer{//...@OverrideprotectedFilter[]getServletFilters(){returnnewFilter[]{newHiddenHttpMethodFilter(),newCharacterEncodingFilter()};}}Eachfilterisaddedwithadefaultnamebasedonitsconcretetypeandautomaticallymappedtothe
DispatcherServlet.The
isAsyncSupported
protectedmethodof
AbstractDispatcherServletInitializer
providesasingleplacetoenableasyncsupportonthe
DispatcherServlet
andallfiltersmappedtoit.Bydefault,thisflagissetto
true.Finally,ifyouneedtofurthercustomizethe
DispatcherServlet
itself,youcanoverridethe
createDispatcherServlet
method.1.1.5.ProcessingSameasinSpringWebFluxThe
DispatcherServlet
processesrequestsasfollows:The
WebApplicationContext
issearchedforandboundintherequestasanattributethatthecontrollerandotherelementsintheprocesscanuse.Itisboundbydefaultunderthe
DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE
key.Thelocaleresolverisboundtotherequesttoletelementsintheprocessresolvethelocaletousewhenprocessingtherequest(renderingtheview,preparingdata,andsoon).Ifyoudonotneedlocaleresolving,youdonotneedthelocaleresolver.Thethemeresolverisboundtotherequesttoletelementssuchasviewsdeterminewhichthemetouse.Ifyoudonotusethemes,youcanignoreit.Ifyouspecifyamultipartfileresolver,therequestisinspectedformultiparts.Ifmultipartsarefound,therequestiswrappedina
MultipartHttpServletRequest
forfurtherprocessingbyotherelementsintheprocess.See
MultipartResolver
forfurtherinformationaboutmultiparthandling.Anappropriatehandlerissearchedfor.Ifahandlerisfound,theexecutionchainassociatedwiththehandler(preprocessors,postprocessors,andcontrollers)isexecutedinordertoprepareamodelorrendering.Alternatively,forannotatedcontrollers,theresponsecanberendered(withinthe
HandlerAdapter)insteadofreturningaview.Ifamodelisreturned,theviewisrendered.Ifnomodelisreturned(maybeduetoapreprocessororpostprocessorinterceptingtherequest,perhapsforsecurityreasons),noviewisrendered,becausetherequestcouldalreadyhavebeenfulfilled.The
HandlerExceptionResolver
beansdeclaredinthe
WebApplicationContext
areusedtoresolveexceptionsthrownduringrequestprocessing.Thoseexceptionresolversallowcustomizingthelogictoaddressexceptions.See
Exceptions
formoredetails.TheSpring
DispatcherServlet
alsosupportsthereturnofthe
last-modification-date,asspecifiedbytheServletAPI.Theprocessofdeterminingthelastmodificationdateforaspecificrequestisstraightforward:The
DispatcherServlet
looksupanappropriatehandlermappingandtestswhetherthehandlerthatisfoundimplementsthe
LastModified
interface.Ifso,thevalueofthe
longgetLastModified(request)
methodofthe
LastModified
interfaceisreturnedtotheclient.Youcancustomizeindividual
DispatcherServlet
instancesbyaddingServletinitializationparameters(init-param
elements)totheServletdeclarationinthe
web.xml
file.Thefollowingtableliststhesupportedparameters:Table1.DispatcherServletinitializationparametersParameterExplanationcontextClassClassthatimplements
ConfigurableWebApplicationContext,tobeinstantiatedandlocallyconfiguredbythisServlet.Bydefault,
XmlWebApplicationContext
isused.contextConfigLocationStringthatispassedtothecontextinstance(specifiedby
contextClass)toindicatewherecontextscanbefound.Thestringconsistspotentiallyofmultiplestrings(usingacommaasadelimiter)tosupportmultiplecontexts.Inthecaseofmultiplecontextlocationswithbeansthataredefinedtwice,thelatestlocationtakesspaceNamespaceofthe
WebApplicationContext.Defaultsto
[servlet-name]-servlet.throwExceptionIfNoHandlerFoundWhethertothrowa
NoHandlerFoundException
whennohandlerwasfoundforarequest.Theexceptioncanthenbecaughtwitha
HandlerExceptionResolver
(forexample,byusingan
@ExceptionHandler
controllermethod)andhandledasanyothers.Bydefault,thisissetto
false,inwhichcasethe
DispatcherServlet
setstheresponsestatusto404(NOT_FOUND)withoutraisinganexception.Notethat,if
defaultservlethandling
isalsoconfigured,unresolvedrequestsarealwaysforwardedtothedefaultservletanda404isneverraised.1.1.6.InterceptionAll
HandlerMapping
implementationssupporthandlerinterceptorsthatareusefulwhenyouwanttoapplyspecificfunctionalitytocertainrequests?—?forexample,checkingforaprincipal.Interceptorsmustimplement
HandlerInterceptor
fromtheorg.springframework.web.servlet
packagewiththreemethodsthatshouldprovideenoughflexibilitytodoallkindsofpre-processingandpost-processing:preHandle(..):BeforetheactualhandlerisexecutedpostHandle(..):AfterthehandlerisexecutedafterCompletion(..):AfterthecompleterequesthasfinishedThe
preHandle(..)
methodreturnsabooleanvalue.Youcanusethismethodtobreakorcontinuetheprocessingoftheexecutionchain.Whenthismethodreturns
true,thehandlerexecutionchaincontinues.Whenitreturnsfalse,the
DispatcherServlet
assumestheinterceptoritselfhastakencareofrequests(and,forexample,renderedanappropriateview)anddoesnotcontinueexecutingtheotherinterceptorsandtheactualhandlerintheexecutionchain.See
Interceptors
inthesectiononMVCconfigurationforexamplesofhowtoconfigureinterceptors.Youcanalsoregisterthemdirectlybyusingsettersonindividual
HandlerMapping
implementations.Notethat
postHandle
islessusefulwith
@ResponseBody
and
ResponseEntity
methodsforwhichtheresponseiswrittenandcommittedwithinthe
HandlerAdapter
andbefore
postHandle.Thatmeansitistoolatetomakeanychangestotheresponse,suchasaddinganextraheader.Forsuchscenarios,youcanimplement
ResponseBodyAdvice
andeitherdeclareitasan
ControllerAdvice
beanorconfigureitdirectlyon
RequestMappingHandlerAdapter.1.1.7.ExceptionsSameasinSpringWebFluxIfanexceptionoccursduringrequestmappingoristhrownfromarequesthandler(suchasa
@Controller),the
DispatcherServlet
delegatestoachainof
HandlerExceptionResolver
beanstoresolvetheexceptionandprovidealternativehandling,whichistypicallyanerrorresponse.Thefollowingtableliststheavailable
HandlerExceptionResolver
implementations:Table2.HandlerExceptionResolverimplementationsHandlerExceptionResolverDescriptionSimpleMappingExceptionResolverAmappingbetweenexceptionclassnamesanderrorviewnames.Usefulforrenderingerrorpagesinabrowserapplication.DefaultHandlerExceptionResolverResolvesexceptionsraisedbySpringMVCandmapsthemtoHTTPstatuscodes.Seealsoalternative
ResponseEntityExceptionHandler
and
RESTAPIexceptions.ResponseStatusExceptionResolverResolvesexceptionswiththe
@ResponseStatus
annotationandmapsthemtoHTTPstatuscodesbasedonthevalueintheannotation.ExceptionHandlerExceptionResolverResolvesexceptionsbyinvokingan
@ExceptionHandler
methodina
@Controllerora
@ControllerAdvice
class.See
@ExceptionHandlermethods.ChainofResolversYoucanformanexceptionresolverchainbydeclaringmultiple
HandlerExceptionResolver
beansinyourSpringconfigurationandsettingtheir
order
propertiesasneeded.Thehighertheorderproperty,thelatertheexceptionresolverispositioned.Thecontractof
HandlerExceptionResolver
specifiesthatitcanreturn:a
ModelAndView
thatpointstoanerrorview.Anempty
ModelAndView
iftheexceptionwashandledwithintheresolver.null
iftheexceptionremainsunresolved,forsubsequentresolverstotry,and,iftheexceptionremainsattheend,itisallowedtobubbleuptotheServletcontainer.The
MVCConfig
automaticallydeclaresbuilt-inresolversfordefaultSpringMVCexceptions,for
@ResponseStatus
annotatedexceptions,andforsupportof
@ExceptionHandler
methods.Youcancustomizethatlistorreplaceit.ContainerErrorPageIfanexceptionremainsunresolvedbyany
HandlerExceptionResolver
andis,therefore,lefttopropagateoriftheresponsestatusissettoanerrorstatus(thatis,4xx,5xx),ServletcontainerscanrenderadefaulterrorpageinHTML.Tocustomizethedefaulterrorpageofthecontainer,youcandeclareanerrorpagemappingin
web.xml.Thefollowingexampleshowshowtodoso:<error><location>/error</location></error>Giventheprecedingexample,whenanexceptionbubblesuportheresponsehasanerrorstatus,theServletcontainermakesanERRORdispatchwithinthecontainertotheconfiguredURL(forexample,
/error).Thisisthenprocessedbythe
DispatcherServlet,possiblymappingittoa
@Controller,whichcouldbeimplementedtoreturnanerrorviewnamewithamodelortorenderaJSONresponse,asthefollowingexampleshows:@RestControllerpublicclassErrorController{@RequestMapping(path="/error")publicMap<String,Object>handle(HttpServletRequestrequest){Map<String,Object>map=newHashMap<String,Object>();map.put("status",request.getAttribute("javax.servlet.error.status_code"));map.put("reason",request.getAttribute("javax.servlet.error.mes
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年沈陽大車貨運資格證考試題
- 2025年貴陽貨運從業(yè)資格證考試模擬試題及答案大全解析
- 單位綠化樹木修剪合同范本
- 上水泥合同范本
- 冷庫設備租用合同范本
- 企業(yè)收款合同范本
- 協(xié)議客戶合同范本
- 公路項目總承包合同范本
- 制作樣冊合同范例
- 醫(yī)院食堂購銷合同范本
- 2024年南京旅游職業(yè)學院高職單招語文歷年參考題庫含答案解析
- 《電商直播》 課件 項目一 走入電商直播
- 《中國宮腔鏡診斷與手術臨床實踐指南(2023版)》解讀課件
- 中藥學電子版教材
- GB/T 9535-1998地面用晶體硅光伏組件設計鑒定和定型
- 常用家電維修基礎知識(課堂PPT)
- 楊氏太極拳37式拳譜
- 臥式設備安裝
- 橋梁施工危險源辨識與防控措施
- CFG樁施工記錄表范本
- 在生產(chǎn)過程中物料流轉交接管理規(guī)定(清風出品)
評論
0/150
提交評論