我是靠谱客的博主 俭朴麦片,这篇文章主要介绍SpringBoot引入Thymeleaf,现在分享给大家,希望可以做个参考。

 新建一个Springboot web项目,然后添加以下依赖。

复制代码
1
2
3
4
5
6
7
8
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

 然后在配置文件里面添加如下依赖。

复制代码
1
2
3
4
5
6
7
spring: thymeleaf: cache: false prefix: classpath:/templates/ encoding: UTF-8 #编码 suffix: .html #模板后缀 mode: HTML #模板

配置说明:

cache这一行是将页面的缓存关闭,不然我们改变页面之后可能不能及时看到更改的内容,默认是true。

prefix是配置thymeleaf模板所在的位置。

encoding 是配置thymeleaf文档的编码,后面的就不说了

5. controller配置

 上面我们配置好了环境之后就可以创建一个controller文件夹,然后写一个controller,来测试我们的thymeleaf是否成功引入。顺便创建一个对象。

代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ControllerpublicclassThymeleafController { @GetMapping("/getStudents")public ModelAndView getStudent(){ List<Student> students = newLinkedList<>(); Studentstudent=newStudent(); student.setId(1); student.setName("全栈学习笔记"); student.setAge(21); Studentstudent1=newStudent(); student1.setId(2); student1.setName("张三"); student1.setAge(22); students.add(student); students.add(student1); ModelAndViewmodelAndView=newModelAndView(); modelAndView.addObject("students",students); modelAndView.setViewName("students"); return modelAndView; } }

代码解释 :我们创建一个list,然后在list里面添加数据,一遍一次将数据传到页面使用。然后我们创建一个ModelAndView的对象,将list放入这个modeAndView对象中,第一个参数是需要放到model中的属性名称相当于是一个键,第二个是,是一个对象。然后利用setViewName方法,设置要跳转的页面或者说是将数据传到对应的页面

 最外层我们使用了一个 @Controller,这个注解是用来返回一个页面或者视图层的。

 当然,返回ModelAndView对象只是一种方法,还有其他的方法,比如说下面这样

复制代码
1
2
3
4
5
@RequestMapping("/getString")public String getString(HttpServletRequest request){ Stringname="全栈学习笔记"; request.setAttribute("name",name); return"index.html"; }

利用http的request传值。

然后还有这样

复制代码
1
2
3
4
@RequestMapping("/getModel")public String getModel(Model model){ model.addAttribute("key","这是一个键"); return"index.html"; }

 去掉末尾的.html也可以,因为我们在配置文件里面设置了文件的格式为HTML文件。return的字符串都是对应的HTML文件的名称。

实体类代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/** * (Student)实体类 * * @author 全栈学习笔记 * @since 2020-04-14 11:39:10 */publicclassStudent { privatestaticfinallongserialVersionUID= -91969758749726312L; /** * 唯一标识id */private Integer id; /** * 姓名 */private String name; /** * 年龄 */private Integer age; //省略get,set方法,自己加上 }

最后

以上就是俭朴麦片最近收集整理的关于SpringBoot引入Thymeleaf的全部内容,更多相关SpringBoot引入Thymeleaf内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(85)

评论列表共有 0 条评论

立即
投稿
返回
顶部