一、在pom.xml中添加对thymeleaf的引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、修改StudentController控制器
package com.example.demo.controller;
import com.example.beans.Student;
import com.example.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class StudentController {
private StudentService studentService=new StudentService();
@RequestMapping("/")
@ResponseBody
public String index(){
return "Hello spring boot";
}
@RequestMapping("/showStudents")
public String showStudents(Model model){
String name="";
for(Student s:studentService.showAllStudents()){
name=name+s.getName()+" ";
}
model.addAttribute("name",name);
return "/Student/StudentsInfo";
}
}
三、在Resources下的templates下创建目录Student,在其下面新建 StudentInfo.html文件,内容如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>所有学生信息</title>
</head>
<body>
<h3 th:text="${name}"></h3>
</body>
</html>
四、说明
@RestController注解相当于@ResponseBody + @Controller合在一起的作用
1.如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容
2.如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解
3.使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面若返回json等内容到页面,则需要加@ResponseBody注解
五、@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
@RequestMapping 除了修饰方法, 还可来修饰类 :
类定义处: 提供初步的请求映射信息。相对于 WEB 应用的根目录;
方法处: 提供进一步的细分映射信息。 相对于类定义处的 URL。
若类定义处未标注 @RequestMapping,则方法处标记的 URL相对于 WEB 应用的根目录
返回ModelAndView时的url会根据你的 @RequestMapping实际情况组成。
如果类上没有映射,那么url直接就是方法的映射;否则url为类上+方法上映射路径组合。
对应项目jsp位置则是一级路径对应一级文件目录。
如url为/default/index
对应项目中webapp/default/index.jsp
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
【1、 value, method;】
value:指定请求的实际地址,指定的地址可以是URI Template 模式;
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
【2、consumes,produces;】
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
【3、 params,headers;】
params: 指定request中必须包含某些参数值时,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。