← 返回学习路线

SYSTEM

静态资源

Java基础静态资源system
src/content/notes/system/静态资源.md

静态资源

访问规则

默认的静态资源路径是 classpath 下的,优先级由高到低为:/META-INF/resources、/resources、 /static、/public 的包内,/ 表示当前项目的根路径

静态映射 /** ,表示请求 / + 静态资源名 就直接去默认的资源路径寻找请求的资源

处理原理:静请求去寻找 Controller 处理,不能处理的请求就会交给静态资源处理器,静态资源也找不到就响应 404 页面


欢迎页面

静态资源路径下 index.html 默认作为欢迎页面,访问 http://localhost:8080 出现该页面,使用 welcome page 功能不能修改前缀

网页标签上的小图标可以自定义规则,把资源重命名为 favicon.ico 放在静态资源目录下即可


源码分析

SpringMVC 功能的自动配置类 WebMvcAutoConfiguration:

public class WebMvcAutoConfiguration {
    //当前项目的根路径
    private static final String SERVLET_LOCATION = "/";
}
  • 内部类 WebMvcAutoConfigurationAdapter:

    @Import(EnableWebMvcConfiguration.class)
    // 绑定 spring.mvc、spring.web、spring.resources 相关的配置属性
    @EnableConfigurationProperties({ WebMvcProperties.class,ResourceProperties.class, WebProperties.class })
    @Order(0)
    public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
    	//有参构造器所有参数的值都会从容器中确定
        public WebMvcAutoConfigurationAdapter(/*参数*/) {
    			this.resourceProperties = resourceProperties.hasBeenCustomized() ? resourceProperties
    					: webProperties.getResources();
    			this.mvcProperties = mvcProperties;
    			this.beanFactory = beanFactory;
    			this.messageConvertersProvider = messageConvertersProvider;
    			this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
    			this.dispatcherServletPath = dispatcherServletPath;
    			this.servletRegistrations = servletRegistrations;
    			this.mvcProperties.checkConfiguration();
    	}
    }
    • ResourceProperties resourceProperties:获取和 spring.resources 绑定的所有的值的对象
    • WebMvcProperties mvcProperties:获取和 spring.mvc 绑定的所有的值的对象
    • ListableBeanFactory beanFactory:Spring 的 beanFactory
    • HttpMessageConverters:找到所有的 HttpMessageConverters
    • ResourceHandlerRegistrationCustomizer:找到 资源处理器的自定义器。
    • DispatcherServletPath:项目路径
    • ServletRegistrationBean:给应用注册 Servlet、Filter
  • WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.addResourceHandler():两种静态资源映射规则

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置文件设置 spring.resources.add-mappings: false,禁用所有静态资源
        if (!this.resourceProperties.isAddMappings()) {
            logger.debug("Default resource handling disabled");//被禁用
            return;
        }
        //注册webjars静态资源的映射规则	映射			路径
        addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        //注册静态资源路径的映射规则		 默认映射 staticPathPattern = "/**" 
        addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            //staticLocations = CLASSPATH_RESOURCE_LOCATIONS
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (this.servletContext != null) {
                ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
                registration.addResourceLocations(resource);
            }
        });
    }
    @ConfigurationProperties("spring.web")
    public class WebProperties {
        public static class Resources {
        	//默认资源路径,优先级从高到低
        	static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
                                                     "classpath:/resources/", 
                                                     "classpath:/static/", "classpath:/public/" }
            private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
            //可以进行规则重写
            public void setStaticLocations(String[] staticLocations) {
    			this.staticLocations = appendSlashIfNecessary(staticLocations);
    			this.customized = true;
    		}
        }
    }
  • WebMvcAutoConfiguration.EnableWebMvcConfiguration.welcomePageHandlerMapping():欢迎页

    //spring.web 属性
    @EnableConfigurationProperties(WebProperties.class)
    public static class EnableWebMvcConfiguration {
        @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(/*参数*/) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
                new TemplateAvailabilityProviders(applicationContext), 
                applicationContext, getWelcomePage(),
                //staticPathPattern = "/**"
                this.mvcProperties.getStaticPathPattern());
            return welcomePageHandlerMapping;
        }
    }
    WelcomePageHandlerMapping(/*参数*/) {
        //所以限制 staticPathPattern 必须为 /** 才能启用该功能
        if (welcomePage != null && "/**".equals(staticPathPattern)) {
            logger.info("Adding welcome page: " + welcomePage);
            //重定向
            setRootViewName("forward:index.html");
        }
        else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
            logger.info("Adding welcome page template: index");
            setRootViewName("index");
        }
    }

    WelcomePageHandlerMapping,访问 / 能访问到 index.html


Rest映射

开启 Rest 功能

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true   #开启页面表单的Rest功能

源码分析,注入了 HiddenHttpMethodFilte 解析 Rest 风格的访问:

public class WebMvcAutoConfiguration {
    @Bean
	@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
	@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled")
	public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
		return new OrderedHiddenHttpMethodFilter();
	}
}

详细源码解析:SpringMVC → 基本操作 → Restful → 识别原理

Web 部分源码详解:SpringMVC → 运行原理