1.开发环境
JDK:1.8
Intellij IDEA
2.新建项目
首先新建项目:
然后设置项目名称,jdk选1.8。
选Spring Web和Thymeleaf。
建好项目以后点运行,可能会报这个错误:
产生这个错误的原因是springboot的自动配置,可以在application.properties文件中配置数据库连接信息:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3366/test?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=111111
可以通过排除自动配置来解决:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3.测试
新建一个控制器类:
@Controller
@RequestMapping("/t1")
public class TestController {
private final String s1 = "hello world";
@RequestMapping("/t2")
public String test(HttpServletRequest request){
request.setAttribute("s1",s1);
return "test";
}
}
在templates创建test.html文件:
test.html文件:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>thymeleaf测试</title>
</head>
<body>
<h3>thymeleaf测试</h3>
<span th:text="${s1}"></span>
</body>
</html>
点击运行,在浏览器中输入:http://localhost:8080/t1/t2:
github地址:https://github.com/lh04140/demo.git