@ResponseBody注解
@ResponseBody 注解可被应用于方法上,标志该方法的返回值应该被直接写回到 HTTP 响应体中去(而不会被被放置到 Model中 或 被解释为一个视图名)
springboot可以通过 controller 跳转:注入的时候一定要是@Controller,而不要是@RestController,因为它是 rest 接口(json格式)是解析不到 html的。
1.配置文件pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--保证配置文件能被扫描到-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.html</include>
</includes>
</resource>
</resources>
2.在配置文件application.properties中关闭Thymeleaf的页面缓存:
# 在构建URL时预先查看名称的前缀,写/templates/也可以
spring.thymeleaf.prefix=classpath:/templates/
#1.把视图页面放到文件夹中
spring.web.resources.static-locations=classpath:/templates
#关闭缓存 # 关闭thymeleaf缓存 开发时使用 否则没有实时画面
spring.thymeleaf.cache=false
# 构建URL时附加查看名称的后缀.
spring.thymeleaf.suffix=.html
3.controller:使用ModelAndView进行页面跳转
@PostMapping(value = "/login")
public ModelAndView login(User user){
Result result = new Result();
result.setSuccess(false);
result.setDetail(null);
QueryWrapper<User> wrapper = new QueryWrapper<>();
//查询条件
wrapper.eq("username", user.getUsername()).eq("password",user.getPassword());
System.out.println(user);
// 查询的数据超过一条时,会抛出异常
User user1 = userService.getOne(wrapper);
if (user1 != null) {
// 如果用户已经存在
result.setMsg("登录成功");
result.setSuccess(true);
result.setDetail(user1);
} else {
result.setMsg("用户或密码错误");
}
ModelAndView mv = new ModelAndView("index");
return mv;
}