【SpringBoot】实现首页映射

下面是来自springboot-features-developing-web-applications中的一段话:
在这里插入图片描述
翻译:" 如果你想要保留springboot mvc的特点,但是想要添加一些额外的mvc配置(拦截器、格式化程序、视图控制器和其他特性),你可以自己创建一个带有@Configuration注解的类并且实现WebMvcConfigurer接口,但是不能带有@EnableWebMvc注解。如果您希望提供的定制情况RequestMappingHandlerMappingRequestMappingHandlerAdapter或者 ExceptionHandlerExceptionResolver,你可以声明一个WebMvcRegistrationsAdapter 实例来提供这样的组件。

如果你想要完全的控制spring mvc,那么你可以在你创建的类中添加@Configuration@EnableWebMvc注解 "


当我们使用的thymeleaf(模版引擎)之后,html页面就只能放在指定的页面(templates)下面,这就导致一个问题——必须通过controller跳转到HTML页面。这就带来一个问题,我们首页应该怎么解决呢? 下面我们将介绍两个方式解决上述的问题。

第一种方式:通过controller进行视图控制

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DemoController {

    @RequestMapping({"/","/index.html"})
    public String index(){
        return "index";
    }
}

第二种方式:通过"添加视图控制器"来实现

springboot-features-developing-web-applications中,我们可知,我们可以通过通过创建自己的类实现对spring mvc的扩展,如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfig implements WebMvcConfigurer {

    // 配置首页视图控制器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

经过上述的两种方式后,我们就可以将url为http://localhost:8080/http://localhost:8080/index.html转换成http://localhost:8080/index



理想如星辰,我们要像航海者一样,借星光的位置而航行…
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值