一、Web开发
Thmyeleaf优点,在原型的代码中,动态人员无需改变代码,就可以实现动态的数据,互不影响, 静态的数据依然未改变
1、pom.xml中加入所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、在application.xml把缓存关闭
spring
thymeleaf:
cache: false
3、在controller中,将数据渲染到index页面上
@RequestMapping("index")
public ModelAndView index(ModelAndView mav) {
mav.setViewName("index");
mav.addObject("index", "hi lucky!");
return mav;
}
4、在templates下创建一个index.html的文件
<div th:text="${index}">哈哈哈哈哈</div>
5、测试
原有的静态数据:
th后端的动态数据:
二、Echarts图表是百度开源的一个前端组件,基于 JavaScript 的开源可视化图表库
官方网站:https://echarts.apache.org/zh/index.html
1、使用图形
按照上方的1、2步骤,用文本打开,复制到html页面中,即可快速使用
注意:把<html style="height: 100%">
设高为100%,否则会被挤压变很小
三、实现文件上传
1、导入Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、在application.xml文件中添加文件上传成功的路径file: upload: path: /f:/hello/
3、在templates下创建一个upload.html为上传的页面
<h1>文件上传页面</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
选择要上传的文件:<input type="file" name="file"><br>
<hr>
<input type="submit" value="提交"> </form>
4、创建上传文件的处理控制器,UploadController
@Value("${file.upload.path}")
private String path;
@GetMapping("/")
public String uploadPage() {
return "upload";
}
@RequestMapping("upload")
@ResponseBody
public String upload(@RequestPart MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = path + fileName;
File dest = new File(filePath);
Files.copy(file.getInputStream(), dest.toPath());
return "Upload file success : " + dest.getAbsolutePath();
}
5、测试,访问url路径:http://localhost:8080/,如果返回的是字符串而不是页面,只需把RestController改为Controller即可
四、多文件上传
1、修改upload.html中的表单文件1:<input type="file" name="files"><br> 文件2:<input type="file" name="files"><br>
2、修改后端处理接口
@PostMapping("/upload")
@ResponseBody
public String create(@RequestPart MultipartFile[] files) throws IOException {
StringBuffer message = new StringBuffer();
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
String filePath = path + fileName;
File dest = new File(filePath);
Files.copy(file.getInputStream(), dest.toPath());
message.append("Upload file success : " + dest.getAbsolutePath()).append("<br>");
}
return message.toString();
}
几个重要改动:
MultipartFile使用数组,参数名称files对应html页面中input的name,一定要对应。
后续处理文件的主体(for循环内)跟之前的一样,就是对MultipartFile数组通过循环遍历的方式对每个文件进行存储,然后拼接结果返回信息。
3、测试,访问url路径:http://localhost:8080/