从SpringMVC源码分析原理

1.SpringMVC下获取web资源的功能实现

WebMvcAutoConfiguration(mvc自动配置类)中的添加资源处理器代码如下:

 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比较热门的有jquery,npm,Bootstrap,以maven的方式去import
                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));
                }
           //方法二:获得资源路径
                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }
            }
        }

其中addResourceLocations()方法的意思如下图:
在这里插入图片描述
法二:所有静态资源都会被ResourceProperties映射识别,

//ResourceProperties(资源配置)中的支持的路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

springboot里会自动在resource下给出static文件夹,其优先级:resource>static(默认)》public
总结:
在springboot中,可以使用以下方式处理静态资源

  • webjars loclahost:8080/webjars/
  • public, static,/**,resouces

SpringMVC下定制首页

WebMvcAutoConfiguration(mvc自动配置类)中的获得首页代码如下:

        @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
        //
            return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
        }
        static String[] getResourceLocations(String[] staticLocations) {
            String[] locations = new String[staticLocations.length + WebMvcAutoConfiguration.SERVLET_LOCATIONS.length];
            System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
            System.arraycopy(WebMvcAutoConfiguration.SERVLET_LOCATIONS, 0, locations, staticLocations.length, WebMvcAutoConfiguration.SERVLET_LOCATIONS.length);
            return locations;
        }
        private Optional<Resource> getWelcomePage() {
            String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }
       //index是默认的首页文件名
        private Resource getIndexHtml(String location) {
            return this.resourceLoader.getResource(location + "index.html");
        }

注:springboot中,在template目录下的所有页面只能通过Controller来跳转!给个例子

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class CanController {
    @GetMapping("/first")
    public String say(){
        return "begin";
    }

begin.html中的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>初始测试</title>
    <meta name = "viewpoint" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="webjars/bootstrap/css/bootstrap.css">
</head>
<body role="document">
    <div class="container theme-showcase" role="main">
    <!-- Main jumbotron for a primary marketing message or call to action -->
    <div class="jumbotron">
        <h1>这是一个小测试而已</h1>
        <p>This is a template for Excavator. It includes  a jumbotron.Use it as a starting point to create something more unique..</p>
        <p><a href="CanTranslate.html" class="btn btn-primary btn-lg" role="button">CAN报文解析</a></p>
    </div>
    </div>
    <ul class="main-menu">
        <li>
            <a href="Can.html"><i class="icon-code"></i> CAN报文解析</a>
        </li>
    </ul>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/smile001isme/article/details/106207470
今日推荐