一、加依赖,在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。