【Spring Boot教程】(十):Spring Boot集成thymeleaf模板引擎

Spring Boot推荐使用thymeleaf模板,因为thymeleaf模板使用的是html,可以直接运行,同时因为不需要转换提高了效率。同时为了spring做了使用方法,很方便。注意控制器的@Controller注解一定要注意不要写成@RestController,除此之外,直接返回页面时不要加/,例如index不要写成/index,否则打包为jar包后会无法找到页面

依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置(这个不写也没关系,因为下面的都是默认配置):

spring.thymeleaf.prefix=classpath:/templates/  # 模板目录
spring.thymeleaf.suffix=.html  # 模板后缀
spring.thymeleaf.encoding=UTF-8  # 模板编码
spring.thymeleaf.enabled=true  # 开始thymeleaf模板
spring.thymeleaf.servlet.content-type=text/html  # 使用模板响应类型
springboot.resources.static-location=classpath:/templates/,classpath:/static/  # 修改静态文件目录,这个默认不包含templates

控制器:

@Controller//一定要注意不要写成@RestController
@RequestMapping("/user")
public class UserController {
	@GetMapping("/findAll")
    public String findAll(){
        return "index";//只写页面逻辑名
    }
}

后端传值:

方法一,返回ModelAndView

@Controller
@RequestMapping("/user")
public class TestController {

    @GetMapping("findAll")
    public ModelAndView findAll(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","xiaoming");
        return new ModelAndView("index", map);
    }
}

方法二:model.addAttribute()或request.setAttribute()

@Controller
@RequestMapping("/user")
public class TestController {

    @GetMapping("findAll")
    public String findAll(Model model){
        model.addAttribute("name","xiaoming");
        return "index";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笼中小夜莺

嘿嘿嘿,请用金钱尽情地蹂躏我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值