上海市网站建设,小型展台设计,网站建设公司使用图片侵权使用者有无责任,浙江创业建设公司网站注解配置SpringMVC 
使用配置类和注解代替web.xml和SpringMVC配置文件的功能 
创建初始化类#xff0c;代替web.xml 
在Servlet3.0环境中#xff0c;容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类#xff0c; 如果找到的话就用它来配置Servle…注解配置SpringMVC 
使用配置类和注解代替web.xml和SpringMVC配置文件的功能 
创建初始化类代替web.xml 
在Servlet3.0环境中容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类 如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现名为 SpringServletContainerInitializer这个类反过来又会查找实现WebApplicationInitializer的类并将配 置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现名为 AbstractAnnotationConfigDispatcherServletInitializer当我们的类扩展了 AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候容器会自 动发现它并用它来配置Servlet上下文。 
public class WebInit extends
AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 指定spring的配置类 * return
*/
Overrideprotected Class?[] getRootConfigClasses() {return new Class[]{SpringConfig.class};
}
/**
* 指定SpringMVC的配置类 * return
*/
Overrideprotected Class?[] getServletConfigClasses() {return new Class[]{WebConfig.class};
}
/**
* 指定DispatcherServlet的映射规则即url-pattern * return
*/
Overrideprotected String[] getServletMappings() {return new String[]{/};
}
/**
* 添加过滤器 * return */
Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter encodingFilter  new CharacterEncodingFilter();encodingFilter.setEncoding(UTF-8);encodingFilter.setForceRequestEncoding(true);HiddenHttpMethodFilter hiddenHttpMethodFilter  new
HiddenHttpMethodFilter();return new Filter[]{encodingFilter, hiddenHttpMethodFilter};
} }创建SpringConfig配置类代替spring的配置文件 
Configuration
public class SpringConfig { //ssm整合之后spring的配置信息写在此类中
} 
创建WebConfig配置类代替SpringMVC的配置文件 
Configuration
//扫描组件 ComponentScan(com.atguigu.mvc.controller) //开启MVC注解驱动
EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
//使用默认的servlet处理静态资源
Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer
configurer) {configurer.enable();
}
//配置文件上传解析器
Bean
public CommonsMultipartResolver multipartResolver(){return new CommonsMultipartResolver();}
//配置拦截器
Override
public void addInterceptors(InterceptorRegistry registry) {FirstInterceptor firstInterceptor  new FirstInterceptor();registry.addInterceptor(firstInterceptor).addPathPatterns(/**);}
//配置视图控制/*Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController(/).setViewName(index);}*/
//配置异常映射 /*Override public void
configureHandlerExceptionResolvers(ListHandlerExceptionResolver resolvers) {SimpleMappingExceptionResolver exceptionResolver  new
SimpleMappingExceptionResolver();
Properties prop  new Properties(); prop.setProperty(java.lang.ArithmeticException, error); //设置异常映射
exceptionResolver.setExceptionMappings(prop); //设置共享异常信息的键 exceptionResolver.setExceptionAttribute(ex); resolvers.add(exceptionResolver);
}*/
//配置生成模板解析器
Bean
public ITemplateResolver templateResolver() {WebApplicationContext webApplicationContext 
ContextLoader.getCurrentWebApplicationContext();
// ServletContextTemplateResolver需要一个ServletContext作为构造参数可通过 WebApplicationContext 的方法获得ServletContextTemplateResolver templateResolver  new
ServletContextTemplateResolver(webApplicationContext.getServletContext());templateResolver.setPrefix(/WEB-INF/templates/);templateResolver.setSuffix(.html);templateResolver.setCharacterEncoding(UTF-8);templateResolver.setTemplateMode(TemplateMode.HTML);return templateResolver;
}
//生成模板引擎并为模板引擎注入模板解析器
Bean
public SpringTemplateEngine templateEngine(ITemplateResolver
templateResolver) {SpringTemplateEngine templateEngine  new SpringTemplateEngine();templateEngine.setTemplateResolver(templateResolver);return templateEngine;
}
//生成视图解析器并未解析器注入模板引擎
Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {ThymeleafViewResolver viewResolver  new ThymeleafViewResolver();viewResolver.setCharacterEncoding(UTF-8);viewResolver.setTemplateEngine(templateEngine);return viewResolver;
}
}测试功能 
RequestMapping(/)
public String index(){return index;
}SpringMVC执行流程 
SpringMVC常用组件 
DispatcherServlet:前端控制器不需要工程师开发由框架提供 作用:统一处理请求和响应整个流程控制的中心由它调用其它组件处理用户的请求HandlerMapping:处理器映射器不需要工程师开发由框架提供 作用:根据请求的url、method等信息查找Handler即控制器方法Handler:处理器需要工程师开发 作用:在DispatcherServlet的控制下Handler对具体的用户请求进行处理HandlerAdapter:处理器适配器不需要工程师开发由框架提供 作用:通过HandlerAdapter对处理器(控制器方法)进行执行ViewResolver:视图解析器不需要工程师开发由框架提供 作用:进行视图解析得到相应的视图例如:ThymeleafView、InternalResourceView、 RedirectViewView:视图 作用:将模型数据通过页面展示给用户 
DispatcherServlet初始化过程 
DispatcherServlet 本质上是一个 Servlet所以天然的遵循 Servlet 的生命周期。所以宏观上是 Servlet 生命周期来进行调度。  
初始化WebApplicationContext 所在类:org.springframework.web.servlet.FrameworkServlet protected WebApplicationContext initWebApplicationContext() {WebApplicationContext rootContext  WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());WebApplicationContext wac  null;if (this.webApplicationContext ! null) {wac  this.webApplicationContext;if (wac instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac  (ConfigurableWebApplicationContext)wac;if (!cwac.isActive()) {if (cwac.getParent()  null) {cwac.setParent(rootContext);}this.configureAndRefreshWebApplicationContext(cwac);}}}if (wac  null) {wac  this.findWebApplicationContext();}if (wac  null) {wac  this.createWebApplicationContext(rootContext);}if (!this.refreshEventReceived) {synchronized(this.onRefreshMonitor) {this.onRefresh(wac);}}if (this.publishContext) {String attrName  this.getServletContextAttributeName();this.getServletContext().setAttribute(attrName, wac);}return wac;}创建WebApplicationContext 所在类:org.springframework.web.servlet.FrameworkServlet 
protected WebApplicationContext createWebApplicationContext(Nullable
ApplicationContext parent) {Class? contextClass  getContextClass();if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass))
{throw new ApplicationContextException(Fatal initialization error in servlet with name  
getServletName() : custom WebApplicationContext class [  contextClass.getName() ] is not of type ConfigurableWebApplicationContext);
}
// 通过反射创建 IOC 容器对象 ConfigurableWebApplicationContext wac (ConfigurableWebApplicationContext)
BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
// 设置父容器
wac.setParent(parent);
String configLocation  getContextConfigLocation(); if (configLocation ! null) {wac.setConfigLocation(configLocation);}configureAndRefreshWebApplicationContext(wac);return wac;
}DispatcherServlet初始化策略 
FrameworkServlet创建WebApplicationContext后刷新容器调用onRefresh(wac)此方法在 DispatcherServlet中进行了重写调用了initStrategies(context)方法初始化策略即初始化 DispatcherServlet的各个组件 
所在类:org.springframework.web.servlet.DispatcherServlet 
protected void initStrategies(ApplicationContext context) {initMultipartResolver(context);initLocaleResolver(context);initThemeResolver(context);initHandlerMappings(context);initHandlerAdapters(context);initHandlerExceptionResolvers(context);initRequestToViewNameTranslator(context);initViewResolvers(context);initFlashMapManager(context);
}DispatcherServlet调用组件处理请求 
processRequest() 
FrameworkServlet重写HttpServlet中的service()和doXxx()这些方法中调用了 processRequest(request, response) 
所在类:org.springframework.web.servlet.FrameworkServlet 
protected final void processRequest(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {long startTime  System.currentTimeMillis();Throwable failureCause  null;LocaleContext previousLocaleContext 
LocaleContextHolder.getLocaleContext();LocaleContext localeContext  buildLocaleContext(request);RequestAttributes previousAttributes 
RequestContextHolder.getRequestAttributes();ServletRequestAttributes requestAttributes  buildRequestAttributes(request,
response, previousAttributes);WebAsyncManager asyncManager  WebAsyncUtils.getAsyncManager(request);asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(),
new RequestBindingInterceptor());initContextHolders(request, localeContext, requestAttributes);
try {
// 执行服务doService()是一个抽象方法在DispatcherServlet中进行了重写 doService(request, response);}catch (ServletException | IOException ex) {failureCause  ex;
throw ex; }catch (Throwable ex) {failureCause  ex;throw new NestedServletException(Request processing failed, ex);
}finally {resetContextHolders(request, previousLocaleContext, previousAttributes);if (requestAttributes ! null) {requestAttributes.requestCompleted();}logResult(request, response, failureCause, asyncManager);publishRequestHandledEvent(request, response, startTime, failureCause);}
}doService 所在类:org.springframework.web.servlet.DispatcherServlet 
Override
protected void doService(HttpServletRequest request, HttpServletResponse
response) throws Exception {
logRequest(request);// Keep a snapshot of the request attributes in case of an include,// to be able to restore the original attributes after the include.MapString, Object attributesSnapshot  null;if (WebUtils.isIncludeRequest(request)) {attributesSnapshot  new HashMap();Enumeration? attrNames  request.getAttributeNames();while (attrNames.hasMoreElements()) {String attrName  (String) attrNames.nextElement();if (this.cleanupAfterInclude ||
attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {attributesSnapshot.put(attrName,
request.getAttribute(attrName));
} }
}// Make framework objects available to handlers and view objects.request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE,
getWebApplicationContext());request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());if (this.flashMapManager ! null) {FlashMap inputFlashMap  this.flashMapManager.retrieveAndUpdate(request,
response);if (inputFlashMap ! null) {request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE,
Collections.unmodifiableMap(inputFlashMap));}request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
}RequestPath requestPath  null;if (this.parseRequestPath 
!ServletRequestPathUtils.hasParsedRequestPath(request)) {requestPath  ServletRequestPathUtils.parseAndCache(request);}
try {
// 处理请求和响应doDispatch(request, response);}
finally { if
(!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {// Restore the original attribute snapshot, in case of an include.if (attributesSnapshot ! null) {restoreAttributesAfterInclude(request, attributesSnapshot);}}if (requestPath ! null) {ServletRequestPathUtils.clearParsedRequestPath(request);}}}      doDispatch() 所在类:org.springframework.web.servlet.DispatcherServlet 
protected void doDispatch(HttpServletRequest request, HttpServletResponse
response) throws Exception {HttpServletRequest processedRequest  request;HandlerExecutionChain mappedHandler  null;boolean multipartRequestParsed  false;WebAsyncManager asyncManager  WebAsyncUtils.getAsyncManager(request);try {ModelAndView mv  null;Exception dispatchException  null;try {processedRequest  checkMultipart(request);multipartRequestParsed  (processedRequest ! request);// Determine handler for the current request./*
mappedHandler:调用链 包含handler、interceptorList、interceptorIndex handler:浏览器发送的请求所匹配的控制器方法 interceptorList:处理控制器方法的所有拦截器集合 interceptorIndex:拦截器索引控制拦截器afterCompletion()的执行
*/mappedHandler  getHandler(processedRequest);if (mappedHandler  null) {noHandlerFound(processedRequest, response);return; }
// Determine handler adapter for the current request.
// 通过控制器方法创建相应的处理器适配器调用所对应的控制器方法 HandlerAdapter ha  getHandlerAdapter(mappedHandler.getHandler());// Process last-modified header, if supported by the handler.String method  request.getMethod();boolean isGet  GET.equals(method);if (isGet || HEAD.equals(method)) {long lastModified  ha.getLastModified(request, mappedHandler.getHandler());if (new ServletWebRequest(request,
response).checkNotModified(lastModified)  isGet) {return;}
}
// 调用拦截器的preHandle()
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;}// Actually invoke the handler.
// 由处理器适配器调用具体的控制器方法最终获得ModelAndView对象mv  ha.handle(processedRequest, response,
mappedHandler.getHandler());if (asyncManager.isConcurrentHandlingStarted()) {return;
}
applyDefaultViewName(processedRequest, mv);
// 调用拦截器的postHandle()mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {dispatchException  ex;
}
catch (Throwable err) {// As of 4.3, were processing Errors thrown from handler methods as well,// making them available for ExceptionHandler methods and other scenarios.dispatchException  new NestedServletException(Handler dispatch
failed, err);
}
// 后续处理:处理模型数据和渲染视图processDispatchResult(processedRequest, response, mappedHandler, mv,
dispatchException);}catch (Exception ex) {triggerAfterCompletion(processedRequest, response, mappedHandler, ex);}catch (Throwable err) {triggerAfterCompletion(processedRequest, response, mappedHandler,new NestedServletException(Handler processing
failed, err));}finally {if (asyncManager.isConcurrentHandlingStarted()) {// Instead of postHandle and afterCompletionif (mappedHandler ! null) {mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);}
} else {// Clean up any resources used by a multipart request.if (multipartRequestParsed) {cleanupMultipart(processedRequest);} }} 
}processDispatchResult() private void processDispatchResult(HttpServletRequest request, HttpServletResponse response, Nullable HandlerExecutionChain mappedHandler, Nullable ModelAndView mv, Nullable Exception exception) throws Exception {boolean errorView  false;if (exception ! null) {if (exception instanceof ModelAndViewDefiningException) {this.logger.debug(ModelAndViewDefiningException encountered, exception);mv  ((ModelAndViewDefiningException)exception).getModelAndView();} else {Object handler  mappedHandler ! null ? mappedHandler.getHandler() : null;mv  this.processHandlerException(request, response, handler, exception);errorView  mv ! null;}}// Did the handler return a view to render?if (mv ! null  !mv.wasCleared()) {// 处理模型数据和渲染视图this.render(mv, request, response);if (errorView) {WebUtils.clearErrorRequestAttributes(request);}} else if (this.logger.isTraceEnabled()) {this.logger.trace(No view rendering, null ModelAndView returned.);}if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {if (mappedHandler ! null) {// Exception (if any) is already handled..// 调用拦截器的afterCompletion()mappedHandler.triggerAfterCompletion(request, response, (Exception)null);}}}SpringMVC的执行流程 
用户向服务器发送请求请求被SpringMVC 前端控制器 DispatcherServlet捕获。DispatcherServlet对请求URL进行解析得到请求资源标识符(URI)判断请求URI对应的映射: a) 不存在 i. 再判断是否配置了mvc:default-servlet-handler ii. 如果没配置则控制台报映射查找不到客户端展示404错误  b) 存在,则执行下面的流程根据该URI调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及 Handler对象对应的拦截器)最后以HandlerExecutionChain执行链对象的形式返回。DispatcherServlet 根据获得的Handler选择一个合适的HandlerAdapter。如果成功获得HandlerAdapter此时将开始执行拦截器的preHandler(…)方法【正向】提取Request中的模型数据填充Handler入参开始执行Handler(Controller)方法处理请求。 在填充Handler的入参过程中根据你的配置Spring将帮你做一些额外的工作: a) HttpMessageConveter: 将请求消息(如Json、xml等数据)转换成一个对象将对象转换为指定 的响应信息 b) 数据转换:对请求消息进行数据转换。如String转换成Integer、Double等 c) 数据格式化:对请求消息进行数据格式化。 如将字符串转换成格式化数字或格式化日期等 d) 数据验证: 验证数据的有效性(长度、格式等)验证结果存储到BindingResult或Error中Handler执行完成后向DispatcherServlet 返回一个ModelAndView对象。此时将开始执行拦截器的postHandle(…)方法【逆向】。根据返回的ModelAndView(此时会判断是否存在异常:如果存在异常则执行 HandlerExceptionResolver进行异常处理)选择一个适合的ViewResolver进行视图解析根据Model 和View来渲染视图。渲染视图完毕执行拦截器的afterCompletion(…)方法【逆向】。将渲染结果返回给客户端。 文章转载自: http://www.morning.kmprl.cn.gov.cn.kmprl.cn http://www.morning.zrrgx.cn.gov.cn.zrrgx.cn http://www.morning.xqjrg.cn.gov.cn.xqjrg.cn http://www.morning.xykst.cn.gov.cn.xykst.cn http://www.morning.wpmqq.cn.gov.cn.wpmqq.cn http://www.morning.dmtwz.cn.gov.cn.dmtwz.cn http://www.morning.bfmq.cn.gov.cn.bfmq.cn http://www.morning.wqfzx.cn.gov.cn.wqfzx.cn http://www.morning.qcbhb.cn.gov.cn.qcbhb.cn http://www.morning.ggxbyhk.cn.gov.cn.ggxbyhk.cn http://www.morning.supera.com.cn.gov.cn.supera.com.cn http://www.morning.nkpls.cn.gov.cn.nkpls.cn http://www.morning.jbxmb.cn.gov.cn.jbxmb.cn http://www.morning.xzrbd.cn.gov.cn.xzrbd.cn http://www.morning.xkzr.cn.gov.cn.xkzr.cn http://www.morning.smmrm.cn.gov.cn.smmrm.cn http://www.morning.rsqpc.cn.gov.cn.rsqpc.cn http://www.morning.rbkml.cn.gov.cn.rbkml.cn http://www.morning.qjdqj.cn.gov.cn.qjdqj.cn http://www.morning.cfqyx.cn.gov.cn.cfqyx.cn http://www.morning.wyrkp.cn.gov.cn.wyrkp.cn http://www.morning.yrjkz.cn.gov.cn.yrjkz.cn http://www.morning.xhftj.cn.gov.cn.xhftj.cn http://www.morning.bhwll.cn.gov.cn.bhwll.cn http://www.morning.ptmgq.cn.gov.cn.ptmgq.cn http://www.morning.pcngq.cn.gov.cn.pcngq.cn http://www.morning.sh-wj.com.cn.gov.cn.sh-wj.com.cn http://www.morning.jjtwh.cn.gov.cn.jjtwh.cn http://www.morning.pqnpd.cn.gov.cn.pqnpd.cn http://www.morning.mkygc.cn.gov.cn.mkygc.cn http://www.morning.ai-wang.cn.gov.cn.ai-wang.cn http://www.morning.vjdofuj.cn.gov.cn.vjdofuj.cn http://www.morning.ranglue.com.gov.cn.ranglue.com http://www.morning.stcds.cn.gov.cn.stcds.cn http://www.morning.rgwrl.cn.gov.cn.rgwrl.cn http://www.morning.jftl.cn.gov.cn.jftl.cn http://www.morning.jrslj.cn.gov.cn.jrslj.cn http://www.morning.kxwsn.cn.gov.cn.kxwsn.cn http://www.morning.zwndt.cn.gov.cn.zwndt.cn http://www.morning.xppj.cn.gov.cn.xppj.cn http://www.morning.nhgfz.cn.gov.cn.nhgfz.cn http://www.morning.ppqjh.cn.gov.cn.ppqjh.cn http://www.morning.jlthz.cn.gov.cn.jlthz.cn http://www.morning.bdypl.cn.gov.cn.bdypl.cn http://www.morning.jkzjs.cn.gov.cn.jkzjs.cn http://www.morning.njntp.cn.gov.cn.njntp.cn http://www.morning.yodajy.cn.gov.cn.yodajy.cn http://www.morning.gqtzb.cn.gov.cn.gqtzb.cn http://www.morning.fpxms.cn.gov.cn.fpxms.cn http://www.morning.wqpb.cn.gov.cn.wqpb.cn http://www.morning.lnmby.cn.gov.cn.lnmby.cn http://www.morning.wztnh.cn.gov.cn.wztnh.cn http://www.morning.wfhnz.cn.gov.cn.wfhnz.cn http://www.morning.nmbbt.cn.gov.cn.nmbbt.cn http://www.morning.rkkh.cn.gov.cn.rkkh.cn http://www.morning.fkyqm.cn.gov.cn.fkyqm.cn http://www.morning.xldpm.cn.gov.cn.xldpm.cn http://www.morning.gtmdq.cn.gov.cn.gtmdq.cn http://www.morning.fcwxs.cn.gov.cn.fcwxs.cn http://www.morning.kwjyt.cn.gov.cn.kwjyt.cn http://www.morning.qpqcq.cn.gov.cn.qpqcq.cn http://www.morning.chxsn.cn.gov.cn.chxsn.cn http://www.morning.qsyyp.cn.gov.cn.qsyyp.cn http://www.morning.rgpsq.cn.gov.cn.rgpsq.cn http://www.morning.uqrphxm.cn.gov.cn.uqrphxm.cn http://www.morning.kmbgl.cn.gov.cn.kmbgl.cn http://www.morning.tsgxz.cn.gov.cn.tsgxz.cn http://www.morning.kdfqx.cn.gov.cn.kdfqx.cn http://www.morning.mdgpp.cn.gov.cn.mdgpp.cn http://www.morning.gyqnp.cn.gov.cn.gyqnp.cn http://www.morning.tjwfk.cn.gov.cn.tjwfk.cn http://www.morning.lskrg.cn.gov.cn.lskrg.cn http://www.morning.hrnrx.cn.gov.cn.hrnrx.cn http://www.morning.nlryq.cn.gov.cn.nlryq.cn http://www.morning.txfxy.cn.gov.cn.txfxy.cn http://www.morning.qjfkz.cn.gov.cn.qjfkz.cn http://www.morning.jwpcj.cn.gov.cn.jwpcj.cn http://www.morning.jrqbr.cn.gov.cn.jrqbr.cn http://www.morning.bsjxh.cn.gov.cn.bsjxh.cn http://www.morning.pqcbx.cn.gov.cn.pqcbx.cn