在SpringBoot项目中,一般都把静态资源放在 static目录 下,而页面放在 templates目录 下

        SpringBoot默认静态资源映射文件夹是 /static/ 或 /public/ 或 /resources/ 或 /META-INF/resources/,并没有 templates目录,那么为什么我们平时使用起来却没有问题呢

        原因是我们一般都整合了thymeleaf,Springboot和thymeleaf的整合中,对templates目录进行了处理,使我们可以通过Controller返回ModelAndView后,间接访问到templates目录下的资源,但是整合了thymeleaf后,也只能通过这种间接的方式访问,而不能直接访问。

        想要直接访问访问thymeleaf目录下的静态资源,SpringBoot静态资源映射文件夹中添加templates目录。

以下举例:

情况一(假设有以下条件):

文件目录:
    resources:
        static:
            index.html
        templates:
            login.html
        application.yaml

application.yaml:    设置视图前缀、后缀
    spring:
      mvc:
        view:
          prefix: /
          suffix: .html

Controller中的方法:
    @RequestMapping("/index")
    public String test1(){
        return "index";
    }

    @RequestMapping("/login")
    public String test2(){
        return "login";
    }

 浏览器发起请求:

1、localhost:8080/index.html    访问index.html成功
2、localhost:8080/index         访问index.html成功

3、localhost:8080/login.html    访问login.html失败
4、localhost:8080/login         访问login.html失败

 情况二(假设有以下条件):

文件目录:
    resources:
        static:
            index.html
        templates:
            login.html
        application.yaml

application.yaml:    设置视图前缀、后缀
    spring:
      mvc:
        view:
          prefix: /
          suffix: .html

Controller中的方法:
    @RequestMapping("/index")
    public String test1(){
        return "index";
    }

    @RequestMapping("/login")
    public String test2(){
        return "login";
    }

pom.xml:    整合了thymeleaf
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

 浏览器发起请求:

1、localhost:8080/index.html    访问index.html成功
2、localhost:8080/index         访问index.html成功

3、localhost:8080/login.html    访问login.html失败
4、localhost:8080/login         访问login.html成功

 情况三(假设有以下条件):

文件目录:
    resources:
        static:
            index.html
        templates:
            login.html
        application.yaml

application.yaml:    设置视图前缀、后缀
    spring:
      mvc:
        view:
          prefix: /
          suffix: .html
      resources:    设置templates目录为映射目录
          static-locations: classpath:/static/,classpath:/templates/

Controller中的方法:
    @RequestMapping("/index")
    public String test1(){
        return "index";
    }

    @RequestMapping("/login")
    public String test2(){
        return "login";
    }

pom.xml:    整合了thymeleaf
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

 浏览器发起请求:

1、localhost:8080/index.html    访问index.html成功
2、localhost:8080/index         访问index.html成功

3、localhost:8080/login.html    访问login.html成功
4、localhost:8080/login         访问login.html失败

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐