一、Spring boot返回视图的方式
1.使用ModelAndView
在controller中
@RequestMapping("toTest")
public ModelAndView toTest(){
ModelAndView mv = new ModelAndView();
//视图名
mv.setViewName("login");
//想传的数据
mv.addObject("o1","数据1");
return mv;
}
2.使用webMVC配置
创建配置类
package com.ch.exercise.config.webMvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* MVC配置
* @author CH
* @date 2021-08-19 11:45
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry
//接收的请求
.addViewController("/toLogin")
//跳转的页面名
.setViewName("login");
}
}
二、补充
快速上手
1.在pom.xml添加依赖
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.创建页面login.html
3.配置thymeleaf
在application.yml中添加上
spring:
thymeleaf:
#页面存放位置
prefix: classpath:/templates/
#是否缓存 这里是否
cache: false
suffix: .html
mode: LEGACYHTML5
template-resolver-order: 0
再进行视图配置就可以访问到了