springboot的使用html页面及css、js路径的配置

1. springboot集成 html页面

在pom.xml文件中增加thymeleaf的starter引用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

springboot项目,在application.yml配置文件中增加如下配置

spring:
  thymeleaf:
    prefix: classpath:/templates
    suffix: .html
    cache: false
    prefix prefix意为前缀 suffix suffix意为后缀

如我的页面为hello-world.html,它所在的目录结构就应该为 resource–> templates --> hello-world.html 在controller中,return的值则为 /hello-world ,系统会自动给加上.html的后缀

然后增加如下controller中就可以访问到hello-world.html页面了

@Controller
@RequestMapping("/")
public class HelloWorldController {

    @RequestMapping("hello-world")
    public String index() {
        return "/hello-world";
    }
   }

2.页面中引用本地js、css文件的路径配置

我的页面中本来都是直接使用的element-ui和vue直接提供的在线js,但是因为页面嵌套会有跨域的问题,所以页面中的js、css都要改为使用本地文件。在网上试了很多的方法,最后使用排除法缩减到最后的方法如下:

    在resource目录下,创建static目录,在static目录下分别创建js目录和css目录来存放js文件和css文件。 在springboot入口的Application文件中增加WebMvc配置,首先继承WebMvcConfigurationSupport类,然后重写addResourceHandlers方法,在里面增加对/css路径和/js路径的映射。 public class ApplicationBootStrap extends WebMvcConfigurationSupport { public static void main(String[] args) { SpringApplication.run(ApplicationBootStrap.class, args); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/css/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/css/"); registry.addResourceHandler("/js/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/js/"); super.addResourceHandlers(registry); } } 页面引用配置 1.html标签 要增加 xmlns:th="http://www.thymeleaf.org" 引用 2.<header>标签中增加 <base th:href="@{/}"> 配置 3.css引入增加 th:href配置路径,js引入增加th:src路径配置。这里要注意link要有 rel="stylesheet" ,script要有type="text/javascript"的格式说明,这是规范。 然后就大功造成了。文件内配置如以下代码。 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <base th:href="@{/}"> <meta charset="UTF-8"> <!-- import CSS --> <link rel="stylesheet" href="../../static/css/index.css" th:href="@{/css/index.css}"/> </head> <body> <div id="app"> </div> </body> <!-- import Vue before Element --> <script src="../../static/js/vue-2.6.12.js" th:src="@{/js/vue-2.6.12.js}" type="text/javascript"></script> <!-- import JavaScript --> <script src="../../static/js/index.js" th:src="@{/js/index.js}" type="text/javascript"></script> <script src="../../static/js/jquery1.7.2.min.js" th:src="@{/js/jquery1.7.2.min.js}" type="text/javascript"></script> <script> let vm = new Vue({ el: #app, .....业务代码省略.... }) </script> </html>
经验分享 程序员 微信小程序 职场和发展