这一篇文章介绍spring boot项目静态资源文件引用的方式:
分两个部分:静态页面加载资源文件和后台java代码加载资源文件
1)举例:页面引用jquery.js
a)引用远程jquery资源,比如这样的
<script type="text/javascript" src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
b)将静态资源jquery.js放到工程目录下引用
注意:spring boot默认会从resource文件夹中读取,这种情况下你会发现页面会发两次请求,一次请求/index,第二次请求/jquery.js
如下图所示:
2)后台java引用资源文件;
加载属性文件people.properties
a)我们把属性文件放到外面,比如目录为:E://people.properties
在Java代码中以流的方式解析
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
/**
* Created by Administrator on 2017/3/22.
*/
@Controller
public class MyController {
@RequestMapping("/index")
public String index(){
//读一个属性文件试试看
readPropertites();
return "index";
}
public void readPropertites(){
Properties properties=new Properties();
try {
InputStream inputStream=new BufferedInputStream(new FileInputStream("E://people.properties"));
properties.load(inputStream);
Iterator<String> it=properties.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
System.out.println("propertites:");
System.out.println(key+" = "+properties.getProperty(key));
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上图的日志很明显已经读出来来属性文件的值
b)属性文件放到本地工程目录下,比如目录:src\main\resources\people.properties
我们这里依然使用页面静态资源引用的b方法试下
代码中我们这样改;
InputStream inputStream=new BufferedInputStream(new FileInputStream("people.properties"));
InputStream inputStream = MyController.class.getResourceAsStream("/people.properties");
整个代码如下:
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
/**
* Created by Administrator on 2017/3/22.
*/
@Controller
public class MyController {
@RequestMapping("/index")
public String index(){
//读一个属性文件试试看
readPropertites();
return "index";
}
public void readPropertites(){
Properties properties=new Properties();
try {
// InputStream inputStream=new BufferedInputStream(new FileInputStream("E://people.properties"));
// InputStream inputStream=new BufferedInputStream(new FileInputStream("people.properties"));
InputStream inputStream = MyController.class.getResourceAsStream("/people.properties");
properties.load(inputStream);
Iterator<String> it=properties.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
System.out.println("propertites:");
System.out.println(key+" = "+properties.getProperty(key));
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}