thymeleaf测试

发布时间 2023-03-22 21:10:55作者: 身带吴钩

thymeleaf是啥?

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP定位类似。是运行在服务器端,不是运行在浏览器端的。所以和Vue不是一个定位,但是确实是一个生态位。换句话说,完全做到前后端分离之后,是不需要用Thymeleaf的,但是做一些简单的页面,可以混合开发。

怎么使用?

1.在Spring工程中引入依赖

在pom文件中,增加如下依赖:

		<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>

2.在工程中设置application.yml

server:
  port: 8080

# thymeleaf 模板
thymeleaf:
  # 开发阶段建议关闭缓存,生产阶段建议开启缓存
  cache: true
  # 编码方式
  encoding: UTF-8
  # 模板模式
  mode: HTML5
  # 指定模板页面路径,默认是 /templates
  # 不对用户开放,会报 404 错误,只能通过转发的方式进行访问
  prefix: classpath:/templates/
  # 后缀名
  suffix: .html

3.增加Controller方法

@SpringBootApplication
@RestController
public class ThymeleafDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(ThymeleafDemoApplication.class, args);
	}

	@RequestMapping(path = "/test.html")
	public ModelAndView toRegister(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response){
//        modelAndView.addObject("username", request.getParameter("username"));
		//简单的keyvalue设置
		modelAndView.addObject("name","thymeleaf 测试页面");
		User user = new User("jim","19","0001110011");
            //添加bean对象
		modelAndView.addObject("user",user);
            //添加list对象
		List fruits = new ArrayList<String>();
		fruits.add("apple");
		fruits.add("banana");
		fruits.add("orange");
		modelAndView.addObject("fruits",fruits);
		modelAndView.setViewName("test");
		return modelAndView;
	}

}

在modelAndView对象中可以支持添加值、bean对象、List对象等。

4.在模板中使用这些值

<body>
<div id="vue_det" class="flexLayout" style="margin-top: 5px;">
    <div th:text="${name}">获取name的值</div>
    <div th:text="${user.getName()}"></div>
    <div th:text="${user.toString()}"></div>

    <h2>List取值</h2>
    <table bgcolor="#ffe4c4" border="1">
        <tr th:each="item:${fruits}">
            <td th:text="${item}"></td>
        </tr>
    </table>

    <div th:object="${user}" >
        <p th:text="*{name}">firstname</p>
    </div>

</div>
</body>