spring boot maven项目thymeleaf模板,后台通过相对路径读取static下txt中文件
1.目录结构
2.java后台根据文件名读取静态资源文件代码
@RequestMapping("/loadFile")
@ResponseBody
public Object loadFile(HttpServletRequest request, HttpServletResponse response) throws IOException{
String fileName = request.getParameter("fileName");
Resource res = new ClassPathResource("static/tempjson/"+fileName+".txt");
return readFile(res.getFile());
}
public static String readFile(File file) {
String result="";
if(file.length()!=0) {
BufferedReader bfReader =null;
try {
InputStream in=new FileInputStream(file);
bfReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String inString ="";
while((inString = bfReader.readLine())!= null){
result+=inString;
}
} catch (Exception e) {
e.printStackTrace();;
}finally {
try {
bfReader.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return result;
}
3.前端页面使用miniui发送链接请求得到后台返回的资源进行显示
<div id="datagrid1" class="mini-datagrid" style="width:100%;height:100%;" allowResize="false"
showPager="false" pageSize="50" idField="year" multiSelect="true" th:attr="[email protected]{/digest/loadFile}">
<div property="columns">
<div header="省份" align="center" headerAlign="center">
<div property="columns">
<div field="prov" width="120" align="center" headerAlign="center">甲</div>
</div>
</div>
<div header="总计 " align="center" headerAlign="center">
<div property="columns">
<div field="total" width="120" align="right" headerAlign="center">1</div>
</div>
</div>
<div header="沥青混凝土" align="center" headerAlign="center">
<div property="columns">
<div field="asphalt" width="120" align="right" headerAlign="center">2</div>
</div>
</div>
<div header="水泥混凝土 " align="center" headerAlign="center">
<div property="columns">
<div field="cement" width="120" align="right" headerAlign="center">3</div>
</div>
</div>
<div header="简易铺装路面 " align="center" headerAlign="center">
<div property="columns">
<div field="simple" width="120" align="right" headerAlign="center">4</div>
</div>
</div>
<div header="未铺装路面 " align="center" headerAlign="center">
<div property="columns">
<div field="unpavedRoads" width="120" align="right" headerAlign="center">5</div>
</div>
</div>
</div>
</div>
<script th:inline="javascript" type="text/javascript">
/*<![CDATA[*/
$(function(){
mini.parse();
mini.get("datagrid1").load({"fileName":"roadType"});
})
/*]]>*/
</script>