1,首先在pom文件中引入模板引擎jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2,在application.properties中配置模板引擎
spring.thymeleaf.prefix=classpath:/templates/
3,在templates下建立test.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>测试</title>
</head>
<body>
测试springboot跳转页面
</body>
</html>
4,写controller
package com.web;
import org.apache.ibatis.annotations.ResultMap;
import org.springframework.stereotype.Controller; i
mport org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestResult {
@RequestMapping("/testGet")
public String testGet()
{ return "test";
}
}
注意:Controller类的注解必须是@Controller,不能写@RestController
知识点:@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
例如:
1.使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面
若返回json等内容到页面,则需要加@ResponseBody注解
public @ResponseBody Result get(RoomAudit roomApplication) {
PageInfo<RoomAudit> pageInfo=roomApplicationService.getPageBySql(roomApplication);
ra = roomApplication;// 记录当前分页设置
if(pageInfo!=null) {
log.info("获取的roomApplication房数量:"+pageInfo.getTotal());
return ResultGenerator.genSuccessResult(pageInfo);
}
else
return ResultGenerator.genFailResult("查询信息失败!");
}
2.@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面