spring boot 学习笔记(一)之前端文件配置

一、叙述

   spring boot 由于是内置的tomcat ,因此其在独立运行的时候,是不需要单独安装 tomcat,这使其前端文件(CSS、JS、html)等放置的位置与war中的不同。

二、常见配置

 要求:服务器上已经安装过 jdk

  将 静态文件放置到 spring boot 工程下的 src/main/resources/static目录下,html 等文件放置到 src/main/resources/templates 下,运行 main函数。目录结构如下:

 其中 含有main 的函数为:TradingSystemApplication.java.  此时运行该函数,服务启动,打开浏览访问,可正常访问网页。

    在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/,经过测试发现 该classpath仅指spring boot 包中的 classes目录:

spring boot 完整 jar 中目录结构如下:

三、特殊要求

(1) 能够访问与 jar 包同级的静态文件

    实现该种功能,主要有以下几种方式:

  • 修改application.properties文件

            配置如下:

spring.mvc.static-path-pattern=/**
#file:css/ 表示包含該jar包的下面的目錄
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
 file:css/,classpath:/static/,classpath:/public/

   file:css/ 在工程中运行时是指:<工程根目录>/css/;

                独立 jar 中运行的时候是指:<包含jar包目录>/css/;

      此时 spring boot 会在css 目录下进行匹配,如访问的静态文件为:http://localhost:8080/context/css/hello.js  ,那么  file:css/ 具体目录下就应该有 css/hello.js 文件,目录结构就是:.../css/css/hello.js。

  • 启动 jar 包时使用 -Dloader.path 命令指定

           独立 jar 包运行的时候,目录结构如下:

  输入的命令如下:

java -Dloader.path=css -jar 2.jar

正常启动之后,打开浏览器进行访问,网页显示正常;

   此时 spring boot 会在css 目录下进行匹配,如访问的静态文件为:http://localhost:8080/context/css/hello.js  ,那么   具体目录下就应该有 css/hello.js 文件,目录结构就是:.../css/css/hello.js。

(2) 能够访问系统中某一具体目录下的静态文件

   修改application.properties文件

       配置内容如下:

#配置静态文件访问地址
casslocation=E:/Program Files/develop/Git/repository/TradingSystem/test

spring.mvc.static-path-pattern=/**

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,file:${casslocation}

   将css及其下的目录放入 E:/Program Files/develop/Git/repository/TradingSystem/test 目录下,运行 含有main 函数的类,服务启动,打开浏览,网页正常显示。

   此时 spring boot 会在test 目录下进行匹配,如访问的静态文件为:http://localhost:8080/context/css/hello.js  ,那么  具体目录下就应该有 css/hello.js 文件,目录结构就是: ../test/css/hello.js

猜你喜欢

转载自www.cnblogs.com/sandyflower/p/10726985.html