当项目中涉及大量的页面跳转,我们可以使用addViewControllers方法实现无业务逻辑跳转,从而减少控制器代码的编写。
addViewControllers方法可以实现将一个请求直接映射为视图,不需要编写控制器来实现,从而简化了页面跳转。
简单示例
Spring Boot项目添加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
假如要访问template路径下的hello.html
添加一个配置类,实现WebMvcConfigurer接口,重写addViewControllers方法。添加@Configuration注解。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("hello");
}
}
效果相当于以下方法:
@GetMapping("hello")
public String hello(){
return "hello";
}
因为thymeleaf默认提供的视图解析器,映射到template目录下,如果要访问页面自定义的目录,就需要在application.properties中配置了。
假设要访问page下的hello2.html:
首先application.properties中添加以下配置:
spring.thymeleaf.prefix=classpath:/page/
spring.thymeleaf.suffix=.html
然后在配置类中
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello2").setViewName("hello2");
}
}
启动项目,在浏览器中访问hello2