1、在pom.xml中添加对thymeleaf的引用html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2、修改StudentController控制器java
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"; } }
3、在Resources下的templates下建立目录Student,在其下面新建 StudentInfo.html文件,内容以下web
<!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>
4、说明spring
@RestController注解至关于@ResponseBody + @Controller合在一块儿的做用json
1.若是只是使用@RestController注解Controller,则Controller中的方法没法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起做用,返回的内容就是Return 里的内容app
2.若是须要返回到指定页面,则须要用 @Controller配合视图解析器InternalResourceViewResolver才行。
若是须要返回JSON,XML或自定义mediaType内容到页面,则须要在对应的方法上加上@ResponseBody注解webapp
3.使用@Controller 注解,在对应的方法上,视图解析器能够解析return 的jsp,html页面,而且跳转到相应页面若返回json等内容到页面,则须要加@ResponseBody注解jsp
5、@RequestMappingspring-boot
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的全部响应请求的方法都是以该地址做为父路径。ui
@RequestMapping 除了修饰方法, 还可来修饰类 :
类定义处: 提供初步的请求映射信息。相对于 WEB 应用的根目录;
方法处: 提供进一步的细分映射信息。 相对于类定义处的 URL。
若类定义处未标注 @RequestMapping,则方法处标记的 URL相对于 WEB 应用的根目录
返回ModelAndView时的url会根据你的 @RequestMapping实际状况组成。
若是类上没有映射,那么url直接就是方法的映射;不然url为类上+方法上映射路径组合。
对应项目jsp位置则是一级路径对应一级文件目录。
如url为/default/index
对应项目中webapp/default/index.jsp
RequestMapping注解有六个属性,下面咱们把她分红三类进行说明。
【一、 value, method;】
value:指定请求的实际地址,指定的地址能够是URI Template 模式;
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
【二、consumes,produces;】
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
【三、 params,headers;】
params: 指定request中必须包含某些参数值时,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。