Spring Boot学习入门之WEB篇

一、整合模板引擎

 由于 jsp 不被 SpringBoot 推荐使用,所以模板引擎主要介绍 Freemarker 和 Thymeleaf。

1.1 整合 Freemarker

1.1.1 添加 Freemarker 依赖

		<!-- freemarker模板引擎 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

1.1.2 在 application.properties中添加

#配置FreeMarker引擎
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.prefix=
spring.freemarker.suffix=.ftl

1.1.3 在 controller 包中创建 FreemarkerController.java

@Controller
@RequestMapping("freemarker")
public class FreemarkerController {
	@RequestMapping("hello")
	public String hello(Map<String, Object> map) {
		map.put("msg", "Hello Freemarker!");
		return "hello";
	}
}

1.1.4 在src/main/resources新建templates文件夹,用于存放ftl模板文件。然后在templates文件夹下新建hello.ftl文件,内容如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="/css/index.css" rel="stylesheet"/>
</head>
<body>
    <div class="container">
        <h2>${msg}</h2>
    </div>
</body>
</html>

运行结果如下:

152944_0s9N_3856404.png

 

1.2 整合Thymeleaf

1.2.1 添加Thymeleaf依赖

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

1.2.2 添加 Thymeleaf 模板配置

在 application.properties 中添加如下内容:

spring.thymeleaf.cache=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

1.2.3 在 controller 包中创建 ThymeleafController:

@Controller
@RequestMapping("thymeleaf")
public class ThymeleafController {
	@RequestMapping("hello")
	public String hello(Map<String, Object> map) {
		map.put("msg", "Hello Thymeleaf");
		return "hello";
	}
}

1.2.4 在 template 目录下创建名为 hello.html 的文件,内容如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="/css/index.css" rel="stylesheet"/>
</head>
<body>
    <div class="container">
        <h1 th:text="${msg}"></h1>
    </div>
</body>
</html>

http://localhost:8080/thymeleaf/hello 结果如下

154001_2Z42_3856404.png

 

 

转载于:https://my.oschina.net/u/3856404/blog/1810862

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值