摘要:本文主要讲解SpringBoot使用Thymeleaf开发web页面。
SpringBoot官方不推荐使用JSP来开发WEB,而是推荐使用如下几种模板引擎来开发:
前面我们讲过(8)SpringBoot整合JSP,这里再以Thymeleaf为例,介绍如何和SpringBoot集成,开发web项目。我们这里新建一个项目,因为之前的项目整合了jsp,如果再次整合Thymeleaf比较麻烦,这里直接新建了(所以本文可以独立参考学习),具体步骤如下:
目录:
<!--Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
server.port=8086
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
配置完之后,当我们接口返回"index"时,会自动解析为
/templates/index.html
我们新建springBoot 的web项目时,目录结构中,resources结构如下:
resources
我们现在在templates下创建一个文件上传页面:upload.html,里面写上简单的文件上传的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>文件上传</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/thymeleaf/uploadBlog">
<p>文件:<input type="file" name="file212"/></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>
如果你新建的目录结构没有templates文件夹,自己新建一个就好,前后缀配置对了就可以找到页面进行跳转。
package com.java4all;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**
* Author: momo
* Date: 2018/4/11
* Description:Thymeleaf页面测试
*/
@Controller
@RequestMapping("thymeleaf")
public class ThymeleafController {
/**
* 跳转到文件上传页面
* @return
*/
@RequestMapping(value = "upload",method = RequestMethod.GET)
public String upload(){
return "upload";
}
/**
* 接收文件
* @param file212
* @return
*/
@RequestMapping(value = "uploadBlog",method = RequestMethod.POST)
@ResponseBody
public String uploadBlog(MultipartFile file212){
String originalFilename = file212.getOriginalFilename();
String name = file212.getName();
return "name:"+name+";=====================originalFilename:"+originalFilename;
}
}
这个类上我们要用@Controller,如果用@RestController,就会返回json格式。 启动项目,我们访问一下:
http://localhost:8086/thymeleaf/upload
页面如下:
选择文件,上传后,页面如下:
项目结构如下: