springboot整合thymeleaf,看这里就够了

本文详细介绍了如何将SpringBoot与Thymeleaf整合。首先在pom.xml中添加Thymeleaf依赖,然后创建templates文件夹存放模板。接着在application.properties中配置Thymeleaf,可以选择简洁或复杂配置。在编写html文件时需引入Thymeleaf的命名空间。在控制器中,使用@Controller和ModelAndView来处理返回页面的情况,而@RestController则用于返回JSON等数据。最后,通过示例展示了如何访问运行后的页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、加依赖,在pom.xml中加入以下依赖

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

 

二、thymeleaf有默认文件路径,在 resources文件夹下新建templates文件夹(这里我是又建了一个子文件thymeleaf)

三、在application.properties中加入配置文件(这里提供两种配置,一种简洁配置,一种复杂一点的配置)

#thymeleaf 简洁配置
spring.thymeleaf.prefix:classpath:/templates/thymeleaf/
spring.thymeleaf.suffix:.html
#thymeleaf 丰富配置
#spring.thymeleaf.prefix=classpath:/templates/thymeleaf/
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.check-template-location=true 
#spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
##缓存设置为false, 这样修改之后马上生效,便于调试
#spring.thymeleaf.cache=false

四、写html文件,login.html(一定要加 <html xmlns:th="http://www.thymeleaf.org">)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>动画注册登录页面</title>

</head>

<body>
<p th:text = "${message}">!!!!</p>
</body>

</html>

五、 写后台,controller

@RestController
//@Controller
@RequestMapping("/springmvc")
public class UserLogin {
	
//	@RequestMapping("/login")
//	public String login(Model model){
//		
//		return "login";
//	}
	@RequestMapping("/login")
public ModelAndView login(Model model){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("login");
		return mv;
	}
}

这里需要注意是用@Controller还是@RestController(看了其他博客)

解释:

1)@RestController注解相当于@ResponseBody+ @Controller合在一起的作用。

如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面或者html页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return里的内容。(直接返回字符串,例如:本来应该到login.html页面的,则其显示login。)

2)如果需要返回到指定页面,则需要用@Controller配合视图解析器InternalResourceViewResolver才行。

3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

重点来了,说了这么多那该如何使用@RestController返回页面呢?这时候要用到ModelAndView;就是我上面写的

六、运行http://localhost:8080/springmvc/login,OK,这里要说的是官方推荐使用@Controller。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值