相关推荐recommended
Thymeleaf模版引擎初尝试
作者:mmseoamin日期:2024-02-22

模版引擎虽然不能够实现代码与视图解耦,但是其适合于个人开发者使用,而且如果存在前后端项目中,前端大量请求后端时,模版引擎无疑也存在优势。

SpringBoot 整合步骤:

  1. 引入依赖
  2. 编写 yml 配置
  3. 编写 html 模版文件
  4. 编写 Controller 接口

    org.springframework.boot
    spring-boot-starter-thymeleaf

spring:
  thymeleaf:
    enabled: true  #开启thymeleaf视图解析
    encoding: utf-8  #编码
    prefix: classpath:/templates/  #前缀
    cache: false  #是否使用缓存
    mode: HTML  #严格的HTML语法模式
    suffix: .html  #后缀名




    
    Title

  

Hello

// 此处使用 @Controller注解 与 ModelAndView 进行视图选择、传参
@Controller
public class User {
    @GetMapping("user")
    ModelAndView get() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user");		// 视图选择
        modelAndView.addObject("username", "小明");		// 传参
        return modelAndView;
    }
}