SpringBoot + thymeleaf开发

1、添加jar
在pom.xml文件中引入需要的jar包。

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/>
	</parent>

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

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

2、配置Application.properties文件

#thymeleaf配置
spring.thymeleaf.cache=false
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

有关thymeleaf其他的配置参考如下文档:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
3、代码部分
java后台代码:

@Controller
public class ApplicationController {
	@RequestMapping("/home")
	@ResponseBody
    public String home() {
        return "hello";
    }
	@RequestMapping("/page")
    public String page(Model model) {
		model.addAttribute("name", "Hello World");
        return "hello";
    }
}

需要注意的是@Controller,如果使用的是@RestController,在测试时显示的不是hello.html页面,显示的是hello。根据官网的解释是@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
建议:
如果只是需要返回JSON,XML或自定义的内容到页面,可以使用@Controller以及在对应的方法上加上@ResponseBody注解或者使用@RestController。如果需要返回到指定页面,则可以使用@Controller,不需要在方法上加上@ResponseBody注解。

具体截图如下:
两个方法返回的都是“hello”字符串,但是page的显示的是hello.html页面,而home显示的是返回的“hello”字符串。
在这里插入图片描述
在这里插入图片描述
hello.html代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>hello world</title>
</head>
<body>
  <div>
     <p><span th:text="${name}"></span></p>
   </div>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值