当前位置: 首页 > news >正文

WebMvc自动配置流程讲解

WebMvc自动配置流程讲解

原理分析

  • 启动springMvc内置的视图解析器ContentNegotiatingViewResolverBeanNameViewResolver
    • ContentNegotiatingViewResolver :并不会解析视图本身,而是委托其他的视图解析器进行解析
      • 所有的视图解析器,都会根据返回的视图名称进行解析视图
@Override
@Nullable
public View resolveViewName(String viewName, Locale locale) throws Exception {RequestAttributes attrs = RequestContextHolder.getRequestAttributes();Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());if (requestedMediaTypes != null) {// 获得所有匹配的视图List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);// 获取最终的视图View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);if (bestView != null) {return bestView;}}

委派给其他解析器进行解析

@Override
protected void initServletContext(ServletContext servletContext) {Collection<ViewResolver> matchingBeans =BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values();if (this.viewResolvers == null) {this.viewResolvers = new ArrayList<>(matchingBeans.size());for (ViewResolver viewResolver : matchingBeans) {if (this != viewResolver) {this.viewResolvers.add(viewResolver);}}}

由以上的代码可以得出结论,它是从Spring IOC容器中获得viewResolver,我们可以自己定制一个viewResolver,ContentNegotiatingViewResolver也会帮我们委派解析

  • BeanNameViewResolver

    • 根据handler方法返回的视图名称 对应到具体视图并解析(定义一个相同名称的类,此类继承一个view(abstractXlsView等等)的接口去生成一个视图)
  • 支持提供静态资源,包括对WebJars的支持

    • WebJars将静态资源放在jar包中进行访问

    • 以前要访问jpg、css、js等这些静态资源文件,需要在web.xml配置,在springboot中不需要配置,只需要放到指定的文件夹中就可以读取出来(约定大于配置)

      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");return;}addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {registration.addResourceLocations(this.resourceProperties.getStaticLocations());if (this.servletContext != null) {ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);registration.addResourceLocations(resource);}});
      }
      

      为什么我们访问http://localhost:8080/image/timssg.jpg也可以访问到图片呢?

    public static class Resources {private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" };/*** Locations of static resources. Defaults to classpath:[/META-INF/resources/,* /resources/, /static/, /public/].*/private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
    
    • 上述代码表示,当图片位于上面的文件中也是可以被读取出来的
  • 自动注册Converter,GenericConverterFormatterBean类

  • 支持HttpMessageConverters

    • HttpMessageConverters负责http请求和响应的报文处理
  • 自动注册MessageCodesResolver

    • 修改错误下的格式转换出错类型转换出错的错误代码
  • 静态index.html支持

    • 在springboot中可以直接返回html的视图

    • 因为在自动WebMvcAutoConfiguration配置类配置

    • 所以就可以通过在配置文件中完成配置

    @Bean
    @ConditionalOnMissingBean
    public InternalResourceViewResolver defaultViewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix(this.mvcProperties.getView().getPrefix());resolver.setSuffix(this.mvcProperties.getView().getSuffix());return resolver;
    }
    
    @Configuration(proxyBeanMethods = false)
    @ConditionalOnWebApplication(type = Type.SERVLET)
    @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
    @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
    @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
    @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,ValidationAutoConfiguration.class })
    public class WebMvcAutoConfiguration {/*** The default Spring MVC view prefix.*/public static final String DEFAULT_PREFIX = "";/*** The default Spring MVC view suffix.*/public static final String DEFAULT_SUFFIX = "";
    
  • 自动使用ConfigurableWebingingInitializer bean

http://www.xdnf.cn/news/1238977.html

相关文章:

  • 研报复现|史蒂夫·路佛价值选股法则
  • 控制建模matlab练习07:比例积分控制-③PI控制器的应用
  • Java ++i 与 i++ 底层原理
  • 学习游戏制作记录(实现克隆攻击的克隆复制和水晶代替克隆)8.3
  • LCL滤波器及其电容电流前馈有源阻尼设计软件【LCLAD_designer】
  • Linux网络编程 --- 多路转接select
  • 07.config 命令实现动态修改配置和慢查询
  • Redis——常用指令汇总指南(三)(哈希类型)
  • Timer实现定时调度的原理是什么?
  • ORA-12514:TNS: 监听程序当前无法识别连接描述符中请求的服务
  • 【2025/08/03】GitHub 今日热门项目
  • 案例介绍|JSON数据格式的转换|pyecharts模块简介
  • 计算机网络(TCP篇)
  • io_setup系统调用及示例
  • C++编译过程与GDB调试段错误和死锁问题
  • 【前端:Html】--1.2.基础语法
  • 源代码本地安装funasr
  • 【Linux网络编程基础--socket地址API】
  • 01数据结构-时间复杂度和空间复杂度
  • FreeRTOS源码分析三:列表数据结构
  • 线程锁-互斥、自旋、读写、原子操作、线程池
  • 江协科技STM32 14-1 WDG看门狗
  • Python篇---环境变量软件安装
  • 【视频内容创作】PR的关键帧动画
  • C++23 Concepts:用类型约束重构泛型编程的终极方案
  • k8s+isulad 国产化技术栈云原生技术栈搭建2-crictl
  • io_cancel系统调用及示例
  • 数据结构:单向链表的函数创建
  • 二叉树的锯齿形层次遍历
  • 思途JSP学习 0802(项目完整流程)