整体分为两个类别:
1、请求完成后直接返回数据。
在pom.xml中不需要配置模板依赖
直接在controller中进行返回数据就好,例如:
package org.xueqi.demo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.xueqi.demo.service.DeptService; @Controller @RequestMapping("jpa") public class JpaDemoController { @Autowired private DeptDao deptDao; @RequestMapping("savdept") public DeptEntiy saveDept() { DeptEntiy dept = new DeptEntiy(); dept.setName("信息中心"); System.out.println("----------------------"); return DeptEntiy; } }
2、请求完成后跳转页面。
需要在pom.xml 中配置模板依赖,springboot 中支持
- FreeMarker
- Groovy
- Thymeleaf
- Velocity(1.4已不再支持)
- Mustache
每种模板依赖的配置信息不同,这里已 Thymeleaf 举例,在xml中加入下面信息
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>1.5.11.RELEASE</version> </dependency>
然后在src/resource/templates 文件下建立你的html文件 ,例如:src/resource/templates 下有一个index.html
然后在controller中这么编辑:
@RequestMapping("html") public String goHtml() { return "index"; }
这里系统就会直接跳转到src/resource/templates文件下的index.html,注意,return "index";中的字符串必须与html文件名一致才行,不然会报404找不到对应的页面错误
3、使用页面模板并且返回数据
这里除了controller和上面的不一样以外其他都一样,这个controller的代码如下:
@RequestMapping("html") public ModelAndView goHtml() { List<DeptEntiy> lst = deptDao.findAll(); ModelAndView model = new ModelAndView("users"); model.addObject("deptLst",lst); return model; }
返回的类型由原来的String变成了ModelAndView ,并且新建了一个ModelAndView来存放我们的数据和视图,其中
new ModelAndView("users") 中的users,对应的就是我们的html文件名
mode.addObject("deptlst",lst) 对应的就是我们返回给页面的数据,return model; 就可以了
页面的代码如下:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>springboot学习</title> </head> <body > <!-- 视图 --> 这是HTML 视图 hahha <div th:each="item : ${deptLst}"> //item就是list集合中的单个实体对象,item.name,就是实体里面的属性名称 <p><a th:text="${{item.name}}"></a></p> </div> </body> </html>
4、这些不是我想要将的重点,我想要说的是一种特殊的情况:
我在学习springboot的时候,自己创建了一个项目,当时是没有引入thymeleaf依赖库的,但是我同样可以使用和访问html,如何这么做呢?
第一:修改项目src/resource/路径下的templates,将其重命名为public
第二:在public下建立一个index.html
这样做的缺点是controller以后无法通过return 来进行页面的跳转,而是需要我们在页面中全部使用ajax访问技术进行页面的再加载。(主要是指利用angular.js 进行服务器的访问与传值)