Spring Boot中使用addViewController实现实现无业务逻辑跳转

当项目中涉及大量的页面跳转,我们可以使用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>
12345678

假如要访问template路径下的hello.html

添加一个配置类,实现WebMvcConfigurer接口,重写addViewControllers方法。添加@Configuration注解。

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/hello").setViewName("hello");
  }
}
1234567

效果相当于以下方法:

  @GetMapping("hello")
  public String hello(){
    return "hello";
  }
1234

因为thymeleaf默认提供的视图解析器,映射到template目录下,如果要访问页面自定义的目录,就需要在application.properties中配置了。

假设要访问page下的hello2.html:

首先application.properties中添加以下配置:

spring.thymeleaf.prefix=classpath:/page/
spring.thymeleaf.suffix=.html
12

然后在配置类中

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/hello2").setViewName("hello2");
  }
​
}
12345678

启动项目,在浏览器中访问hello2

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值