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";
}
}