静态资源处理

SpringBoot中,所有的配置文件,applicatoin.yaml 文件中,并没有web.xml
我们需要想办法来实现,静态资源 .css ,.js 等等,这些文件需要生效,我们就需要明白
他的规则!
1、从源码分析、得出结论!
2、再尝试测试是否有用!
SpringBoot 默认是没有webapp目录的,那我们资源应该放在那里呢?

尝试分析源码,看看有没有对应的代码,然后探究!

1、所有的mvc相关的配置都在 WebMvcAutoConfiguration (视图解析器,静态资源过滤)
2、addResourceHandlers 静态资源处理方法

注:分析源代码,需要掌握看对象的方法调用

  1. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  2. //禁用默认规则的 一个配置,如果你手动的添加了资源映射路径的配置,那么这些自动配置会直接失效!
  3. if (!this.resourceProperties.isAddMappings()) {
  4. logger.debug("Default resource handling disabled");
  5. } else {
  6. //缓存控制
  7. Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
  8. CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
  9. // 判断是否存在一个映射路径 /webjars/**
  10. // addResourceHandler 处理逻辑
  11. // addResourceLocations 处理资源的地址
  12. if (!registry.hasMappingForPattern("/webjars/**")) {
  13. this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
  14. }
  15. //获取静态资源路径 staticPathPattern="/**"
  16. String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  17. if (!registry.hasMappingForPattern(staticPathPattern)) {
  18. this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
  19. }
  20. }
  21. }
  22. //this.resourceProperties.getStaticLocations()
  23. private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
  24. { "classpath:/META-INF/resources/",
  25. "classpath:/resources/", "classpath:/static/",
  26. "classpath:/public/" };

什么是 webjars

使用maven ,然后可以用jar包的方式引入前端静态资源;导入maven依赖

  1. <!-- jquery 的 webjars -->
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.webjars</groupId>
  5. <artifactId>jquery</artifactId>
  6. <version>3.4.1</version>
  7. </dependency>
  8. </dependencies>

发现导入了一个jar包
image.png
我们可以通过
http://localhost:8080/webjars/jquery/3.4.1/jquery.js 来进行访问
这种在我们实际开发中并不常用

分析发现,静态资源处理规则,第二种

  1. private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
  2. {
  3. "classpath:/META-INF/resources/", //一般在starter中使用!SWAGGER-UI
  4. "classpath:/resources/", //一般放文件资源
  5. "classpath:/static/", // 静态资源
  6. "classpath:/public/" // 公共资源 图标。。。
  7. };

即我们的静态资源文件可以放在如下文件夹下:
image.png

访问优先级: /META-INF/resources/ > /resources/ > /static/ > /public/

自定义配置 ,可以自己配置静态资源的映射路径,但是这样配置之后,默认的就会失效

  1. spring.resources.static-locations=classpath:/coding,classpath:/donniz

在配置文件中配置如上目录以后,原来的默认的将会失效。

首页

分析源码

  1. @Bean //首页 会被映射到这个处理器下
  2. public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
  3. WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
  4. welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
  5. welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
  6. return welcomePageHandlerMapping;
  7. }
  8. private Optional<Resource> getWelcomePage() {
  9. String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
  10. return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
  11. }
  12. private Resource getIndexHtml(String location) {
  13. return this.resourceLoader.getResource(location + "index.html");
  14. }

只要在我们上面的静态资源映射目录下存在的index.html 就会被自动映射为首页(欢迎页)

网站图标

  1. public enum StaticResourceLocation {
  2. /**
  3. * Resources under {@code "/css"}.
  4. */
  5. CSS("/css/**"),
  6. /**
  7. * Resources under {@code "/js"}.
  8. */
  9. JAVA_SCRIPT("/js/**"),
  10. /**
  11. * Resources under {@code "/images"}.
  12. */
  13. IMAGES("/images/**"),
  14. /**
  15. * Resources under {@code "/webjars"}.
  16. */
  17. WEB_JARS("/webjars/**"),
  18. /**
  19. * The {@code "favicon.ico"} resource.
  20. */
  21. FAVICON("/**/favicon.ico");
  22. private final String[] patterns;
  23. StaticResourceLocation(String... patterns) {
  24. this.patterns = patterns;
  25. }
  26. public Stream<String> getPatterns() {
  27. return Arrays.stream(this.patterns);
  28. }
  29. }

我们在静态映射路径中添加默认图标即可。

Thymeleaf 模板引擎

模板引擎

什么是模板引擎?
前端给你的页面一般是一些静态资源,html等
传统的话,我们需要将他们转换为jsp页面,嵌入java变量或者代码,来实现一些功能。
jsp 无疑是很强大的!
但是现在的问题:SpringBoot没有办法写jsp页面,jar包的方式运行。而且不是war包
image.png
知名的模板引擎:jsp、freemarker、Thymeleaf
StringBoot 推荐我们使用Thymeleaf 模板引擎;他使用的就是 html页面!

Thymeleaf 使用

1、导入依赖
2、配置
3、使用

MVC自动配置原理

官方文档阅读

学习方式:源码+官方文档!
image.png

ContentNegotiatingViewResolver 内容协商视图解析器

自动配置了ViewResolver ,就是SpringMVC中的视图解析器;
View 、Controller
看源码:

  1. @Bean
  2. @ConditionalOnBean(ViewResolver.class)
  3. @ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
  4. public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
  5. ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
  6. resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));
  7. // ContentNegotiatingViewResolver uses all the other view resolvers to locate
  8. // a view so it should have a high precedence
  9. // ContentNegotiatingViewResolver 使用其他所有的视图解析器定位视图
  10. //因此它应该有一个高的优先级
  11. resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
  12. return resolver;
  13. }

解析视图名字

  1. @Nullable //参数可以为空
  2. public View resolveViewName(String viewName, Locale locale) throws Exception {
  3. RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
  4. Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
  5. List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());
  6. if (requestedMediaTypes != null) {
  7. //获取所有候选的视图
  8. List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);
  9. //获取最好的视图
  10. View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);
  11. //返回最好的视图
  12. if (bestView != null) {
  13. return bestView;
  14. }
  15. }
  16. String mediaTypeInfo = this.logger.isDebugEnabled() && requestedMediaTypes != null ? " given " + requestedMediaTypes.toString() : "";
  17. if (this.useNotAcceptableStatusCode) {
  18. if (this.logger.isDebugEnabled()) {
  19. this.logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo);
  20. }
  21. return NOT_ACCEPTABLE_VIEW;
  22. } else {
  23. this.logger.debug("View remains unresolved" + mediaTypeInfo);
  24. return null;
  25. }
  26. }

既然它是从容器中加载所有的视图解析器,那么我们可以猜想,我们自己写一个视图解析器也可以被扫描并加载。

格式化转换器 Fomatter

  1. @Bean
  2. @Override
  3. public FormattingConversionService mvcConversionService() {
  4. Format format = this.mvcProperties.getFormat();
  5. WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()
  6. .dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));
  7. addFormatters(conversionService);
  8. return conversionService;
  9. }
  10. //源码中默认的格式是通过斜杠 分割的
  11. private String dateFormat;
  12. 只要是在 properties中的 ,都是可以进行手动配置的。

修改SpringBoot配置

官方文档:
image.png
image.png