静态资源处理
SpringBoot中,所有的配置文件,applicatoin.yaml 文件中,并没有web.xml
我们需要想办法来实现,静态资源 .css ,.js 等等,这些文件需要生效,我们就需要明白
他的规则!
1、从源码分析、得出结论!
2、再尝试测试是否有用!
SpringBoot 默认是没有webapp目录的,那我们资源应该放在那里呢?
尝试分析源码,看看有没有对应的代码,然后探究!
1、所有的mvc相关的配置都在 WebMvcAutoConfiguration (视图解析器,静态资源过滤)
2、addResourceHandlers 静态资源处理方法
注:分析源代码,需要掌握看对象的方法调用
public void addResourceHandlers(ResourceHandlerRegistry registry) {//禁用默认规则的 一个配置,如果你手动的添加了资源映射路径的配置,那么这些自动配置会直接失效!if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");} else {//缓存控制Duration cachePeriod = this.resourceProperties.getCache().getPeriod();CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();// 判断是否存在一个映射路径 /webjars/**// addResourceHandler 处理逻辑// addResourceLocations 处理资源的地址if (!registry.hasMappingForPattern("/webjars/**")) {this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}//获取静态资源路径 staticPathPattern="/**"String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) {this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));}}}//this.resourceProperties.getStaticLocations()private static final String[] CLASSPATH_RESOURCE_LOCATIONS ={ "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/","classpath:/public/" };
什么是 webjars
使用maven ,然后可以用jar包的方式引入前端静态资源;导入maven依赖
<!-- jquery 的 webjars --><dependencies><dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.4.1</version></dependency></dependencies>
发现导入了一个jar包
我们可以通过
http://localhost:8080/webjars/jquery/3.4.1/jquery.js 来进行访问
这种在我们实际开发中并不常用
分析发现,静态资源处理规则,第二种
private static final String[] CLASSPATH_RESOURCE_LOCATIONS ={"classpath:/META-INF/resources/", //一般在starter中使用!SWAGGER-UI"classpath:/resources/", //一般放文件资源"classpath:/static/", // 静态资源"classpath:/public/" // 公共资源 图标。。。};
即我们的静态资源文件可以放在如下文件夹下:
访问优先级: /META-INF/resources/ > /resources/ > /static/ > /public/
自定义配置 ,可以自己配置静态资源的映射路径,但是这样配置之后,默认的就会失效
spring.resources.static-locations=classpath:/coding,classpath:/donniz
首页
分析源码
@Bean //首页 会被映射到这个处理器下public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());return welcomePageHandlerMapping;}private Optional<Resource> getWelcomePage() {String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();}private Resource getIndexHtml(String location) {return this.resourceLoader.getResource(location + "index.html");}
只要在我们上面的静态资源映射目录下存在的index.html 就会被自动映射为首页(欢迎页)
网站图标
public enum StaticResourceLocation {/*** Resources under {@code "/css"}.*/CSS("/css/**"),/*** Resources under {@code "/js"}.*/JAVA_SCRIPT("/js/**"),/*** Resources under {@code "/images"}.*/IMAGES("/images/**"),/*** Resources under {@code "/webjars"}.*/WEB_JARS("/webjars/**"),/*** The {@code "favicon.ico"} resource.*/FAVICON("/**/favicon.ico");private final String[] patterns;StaticResourceLocation(String... patterns) {this.patterns = patterns;}public Stream<String> getPatterns() {return Arrays.stream(this.patterns);}}
Thymeleaf 模板引擎
模板引擎
什么是模板引擎?
前端给你的页面一般是一些静态资源,html等
传统的话,我们需要将他们转换为jsp页面,嵌入java变量或者代码,来实现一些功能。
jsp 无疑是很强大的!
但是现在的问题:SpringBoot没有办法写jsp页面,jar包的方式运行。而且不是war包
知名的模板引擎:jsp、freemarker、Thymeleaf
StringBoot 推荐我们使用Thymeleaf 模板引擎;他使用的就是 html页面!
Thymeleaf 使用
MVC自动配置原理
官方文档阅读
学习方式:源码+官方文档!
ContentNegotiatingViewResolver 内容协商视图解析器
自动配置了ViewResolver ,就是SpringMVC中的视图解析器;
View 、Controller
看源码:
@Bean@ConditionalOnBean(ViewResolver.class)@ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));// ContentNegotiatingViewResolver uses all the other view resolvers to locate// a view so it should have a high precedence// ContentNegotiatingViewResolver 使用其他所有的视图解析器定位视图//因此它应该有一个高的优先级resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);return resolver;}
解析视图名字
@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 = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());if (requestedMediaTypes != null) {//获取所有候选的视图List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);//获取最好的视图View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);//返回最好的视图if (bestView != null) {return bestView;}}String mediaTypeInfo = this.logger.isDebugEnabled() && requestedMediaTypes != null ? " given " + requestedMediaTypes.toString() : "";if (this.useNotAcceptableStatusCode) {if (this.logger.isDebugEnabled()) {this.logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo);}return NOT_ACCEPTABLE_VIEW;} else {this.logger.debug("View remains unresolved" + mediaTypeInfo);return null;}}
既然它是从容器中加载所有的视图解析器,那么我们可以猜想,我们自己写一个视图解析器也可以被扫描并加载。
格式化转换器 Fomatter
@Bean@Overridepublic FormattingConversionService mvcConversionService() {Format format = this.mvcProperties.getFormat();WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));addFormatters(conversionService);return conversionService;}//源码中默认的格式是通过斜杠 分割的private String dateFormat;只要是在 properties中的 ,都是可以进行手动配置的。
修改SpringBoot配置
官方文档:

