springboot+thymeleaf HelloWorld!

一、新建springboot项目

1. 访问 http://start.spring.io/,选择构建工具 Maven Project、Java、Spring Boot 版本 2.1.3 以及一些工程基本信息,解压后,使用 Idea 导入项目,File -> New -> Model from Existing Source.. -> 选择解压后的文件夹 -> OK,选择 Maven 

2. 根据mvc分层原则,建立包

 

3. 配置thymeleaf

在application.properties文件中配置如下:

##thymeleaf的配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html


也可以不用配置按照默认的来:可以查看ThymeleafProperties该类,这个类有thymeleaf的默认配置

 

4. 编写html

thymeleaf需要添加:<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">

<p th:text="${session.u}">Welcome to our grocery store!</p>:该写法动态替换<p></p>中的内容

以下是遍历list集合的方式:

<tr th:each="user : ${session.users}">
<td th:text="${user.userName}">user.userName</td>
<td th:text="${user.passWord}">user.passWord</td>
<td th:text="${user.email}">user.email</td>
</tr>

 

5. 编写controller

@RequestMapping(value = "/thy" ,method = RequestMethod.GET)
public String toThyTest(HttpSession session){
session.setAttribute("u","thymeleaf test!!!!!");
List<User> users = new ArrayList<User>();

users.add(new User("小明","111222","ming@qq.com",""));
users.add(new User("小红","1112224","hong1@qq.com",""));
users.add(new User("小王","1112122","wang@qq.com",""));
users.add(new User("小黑","11122322","hei@qq.com",""));
users.add(new User("小白","1112222","bai1@qq.com",""));
session.setAttribute("users",users);

return "thyTest";
}

之后启动应用,浏览器键入http://127.0.0.1:8080/thy,即可访问编写的thyTest.html页面


碰到的几点问题:
1.一开始总是报,cannot find classpath:/templates/ ,一直找不到原因,重新bulid项目之后就好了

2.如果需要返回模板,注意不要使用@RestController, 该注释相当于@Controller和@ResponseBody的综合

 

 

 

 




 

posted on 2019-07-16 17:35 exciak 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/exciak/p/11196366.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值