thymeleaf简单使用
pojo层User类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private int age;
private String username;
}
Controller层中model所绑定的数据:
@RequestMapping("/user/details")
public ModelAndView userDetails(){
ModelAndView mv = new ModelAndView();
User mjoe = new User();
mjoe.setId(1);
mjoe.setAge(19);
mjoe.setUsername("mjoe");
mv.addObject("user",mjoe);
mv.setViewName("userDetails");
return mv;
}
1. 标准变量表达式${}
,
主要用于获取Controller封装在model中的数据
<div>
<h2 th:text="${user.getId()}"></h2>
</div>
<div>
<h2 th:text="${user.id}"></h2>
</div>
2.选择变量表达式*{}
2.1 通过th:Object=“${object}”
绑定Controller model中的一个对象后,在html子标签中使用*{}
可以选择所绑定对象的属性
<div th:object="${user}">
<p>id:<span th:text="*{id}"></span></p>
<p>年龄:<span th:text="*{age}"></span></p>
<p>用户名:<span th:text="*{username}"></span></p>
</div>
2.2 混合使用
<div>
<p>id:<span th:text="*{user.id}"></span></p>
<p>年龄:<span th:text="*{user.age}"></span></p>
<p>用户名:<span th:text="*{user.username}"></span></p>
</div>
3 路径表达式@{}
,
主要用于绑定相对路径(绝对路径没啥区别)
3.1 不带参数
<a href="http://www.baidu.com">普通a标签跳转</a>
<a th:href="@{http://www.baidu.com}">th标签跳转</a>
<a href="http://localhost:8080/dev/thymeleaf/user/details">普通a跳转controller层</a>
<a th:href="@{http://localhost:8080/dev/thymeleaf/user/details}">th标签跳转controller层</a>
<a th:href="@{/thymeleaf/user/details}">th标签跳转controller层</a>
3.2 路径带参数
@RequestMapping("/url")
public ModelAndView url(){
ModelAndView mv = new ModelAndView();
mv.addObject("id",10081);
mv.addObject("username","mjoe");
mv.setViewName("url");
return mv;
}
@RequestMapping("/test")
public @ResponseBody String test(int id, String username){
return "id="+id+",username="+username;
}
<a th:href="@{'/thymeleaf/test?id='+${id}+'&username='+${username}}">跳转到url</a>
<a th:href="@{/thymeleaf/test(id=${id},username=${username})}">tiaohzuan</a>
3.3 带参数的RESTful风格访问路径
@RequestMapping("/url") public ModelAndView url(){ ModelAndView mv = new ModelAndView(); mv.addObject("id",10081); mv.addObject("username","mjoe"); mv.setViewName("url"); return mv; } @RequestMapping("/test/{id}") public @ResponseBody String test(@PathVariable("id") int id){ return "id="+id; }
<a th:href="@{'/thymeleaf/test/'+${id}}">restful</a>
3.4 引入static文件夹中的静态资源
@RequestMapping("/url2")
public ModelAndView url2(){
ModelAndView mv = new ModelAndView();
mv.setViewName("url2");
return mv;
}
<img th:src="@{/img/test.jpg}">
tips:springboot集成的试图解析器会自动给视图路径添加前缀
/templates/
,后缀.html
继承的thymeleaf会自动给静态资源的引用添加
/static
3.5 表单路径
@RequestMapping("/propertity")
public ModelAndView propertity(){
ModelAndView mv = new ModelAndView();
mv.setViewName("propertity");
return mv;
}
@RequestMapping("/test")
public @ResponseBody String test(int id, String username){
return "id="+id+",username="+username;
}
<form th:action="@{/thymeleaf/test}">
用户id:<input type="text" name="id">
用户名:<input type="text" name="username">
<input type="submit" value="提交">
</form>