zoukankan      html  css  js  c++  java
  • 记一次SpringMVC项目转Springboot项目templates和static无法访问以及WebMvcConfigurerAdapter过时失效

    在这次项目升级过程中主要遇到了三个问题

    1、使用Spring5.xx(或者Springboot2.xx)版本来配置WebMVC时,发现WebMvcConfigurerAdapter不能使用,查看源码后发现官方已经废弃了这个抽象类,

      现在官方在源码中推荐的方式是直接实现WebMvcConfigurer 这个接口,通过查看这个接口的源码发现,在接口中的每个方法前都添加了“default”

      在这里说明下“default”是jdk8后的新特性,在这里简要说明下它与抽象类的区别,详细的请查阅相关资料。
    
      default方法作用范围是public,只是有了具体实现的方法体。对已有的接口,如果想对接口增加一个新方法,那么需要对所有实现该接口的类进行修改。
    
      而有了default方法,可以解决该问题,但是需要注意的是public抽象类的abstract method还可以可以是protected,因此在一些方面并不能完全取代抽象类。

      在WebMvcConfigurerAdapter中的每个方法都是public的,所以官方可能为了减少代码量,直接在WebMvcConfigurer接口中使用了default

      以下时在配置WebMVC的代码  

    @Configuration
    // 等价于<mvc:annotation-driven/>
    @EnableWebMvc
    public class MvcConfiguration implements WebMvcConfigurer, ApplicationContextAware {
        // Spring容器
        private ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }

      除了官方推荐的这种方法外,还有第二种方法就是extends WebMvcConfigurationSupport,但是使用这种方法相当于覆盖了@EnableAutoConfiguration里的所有方法,每个方法都需要重写,比如,若不实现方法addResourceHandlers(),则会导致静态资源无法访问,因此需要特别注意。

    2、templates和static无法访问,需要在WebMVC中做如下配置

      

        /**
         * 静态资源配置
         * 
         * @param registry
         */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
             registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");  //如果有templates就解析成类路径下的templates
             registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");  //如果有static就解析成类路径下的static
            // 如果有upload就解析成外部的路径file:/home/o2o/image/upload
            registry.addResourceHandler("upload/**").addResourceLocations("file:/home/o2o/image/upload");
        }

    templates与static的区别通过查阅springboot的相关文档就可以知道,这里不在解释

    如果static中的资源还是无法访问就去查看你的templates下的html页面里面的对于static下面的静态资源的引用路径是否正确,

    我的目录层次结构,以及对static下的静态资源的引用如下

     

      

  • 相关阅读:
    hashmap的一些基础原理
    关于uuid
    读锁跟写锁的区别
    栈为什么效率比堆高
    MySQL行级锁、表级锁、页级锁详细介绍
    MYSQL MyISAM与InnoDB对比
    MYSQL锁表问题解决
    mysql查询锁表语句
    三种排序方法
    正则表达式
  • 原文地址:https://www.cnblogs.com/xing-29391/p/13387007.html
Copyright © 2011-2022 走看看