本篇文章主要介绍springboot集成html,并简单说下四种从后端传数据到页面的方式,这里页面使用的是thymeleaf模板引擎,也是springboot官方推荐的使用方式,学习thymeleaf? https://www.thymeleaf.org/
1、pom.xml中引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、application.yml配置模板路径
spring:
thymeleaf:
prefix: classpath:/templates/
3、controller类
这里说4种传数据到页面得方式:
- @ResponseBody直接返回字符串,可以是普通字符串格式也可以是json格式
- 通过Model传数据,Model类必须作为函数参数使用来传参,在函数里面通过new出来得对象无法传参
- 通过Map传数据,同上,必须作为函数参数来使用
- 通过ModelAndView传数据,ModelAndView可以是函数参数,也可以在函数里面new出来,但是函数返回类型必须是ModelAndView
package com.example.springboot_html;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
/**
* @author XuJD
* @create 2018-10-29 11:58
**/
@Controller
public class IndexController {
@RequestMapping("/index")
@ResponseBody
public String index(){
return "index";
}
@RequestMapping("/index1")
public String index1(Model model,Map<String, Object> map){
map.put("name","map传参");
model.addAttribute("name1","Model传参");
return "index";
}
@RequestMapping("/index2")
public ModelAndView index2(ModelAndView modelAndView){
//ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("name","ModelAndView传参");
modelAndView.addObject("name1","ModelAndView传参");
return modelAndView;
}
}
4、页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${name}"></h1>
<h1 th:text="${name1}"></h1>
</body>
</html>
源码地址:
github下载:https://github.com/xujiangdong/SpringbootLearn