SpringMVC原始碼分析原理

專注的阿熊發表於2020-05-21

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));

                }

            }

        }

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>

<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"MT4

    <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>

        <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>

        <li>

            <a href="Can.html"><i></i> CAN 報文解析 </a>

        </li>

    </ul>

</body>

</html>


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2693480/,如需轉載,請註明出處,否則將追究法律責任。

相關文章