SpringBoot日记——实战篇——Url定向

搞定了SpringBoot的一些基础核心的东西,我们需要实践一个项目来确认自己学习的东西能被应用,最初,我们会选择自己写一个登陆页面,这也是每个网站几乎都有的门面。

在写之前,还有一些知识点需要记录——URL定向。

比如我们访问“/”和访问“/index.html”这样的路径的时候,希望他们都可以指向同一个页面,但是我们又不能写一堆Controller来实现,那样以后维护起来也十分繁琐,所以这里引入了一个Adapter的方法。

 

具体如何实现的呢,先来看代码,然后做讲解:

复制代码
/**
 * 由于SpringBoot2.0之前,我们使用的WebMvcConfigurerAdapter来进行url重定向,现在已经过期了,
 * 而之后我们有两种方法来实现上述的功能:
 * 1.继承 WebMvcConfigurationSupport方法(有两种写法)
 * 2.实现 WebMvcConfigurer接口(这里推荐用这种,相对便捷)
 *
 */// WebMvcConfigurationSupport 写法1
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {
    @Bean
    public WebMvcConfigurationSupport webMvcConfigurationSupport() {
        WebMvcConfigurationSupport support = new WebMvcConfigurationSupport() {
            @Override
            protected void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("index");
                registry.addViewController("/index.html").setViewName("index");
            }

            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/static/**").addResourceLocations("classpath:/resources/static/");
                super.addResourceHandlers(registry);
            }
        };
        return support;
    }
复制代码

--

复制代码
//WebMvcConfigurationSupport 写法2
@Configuration
public class myMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}
复制代码

来看推荐的方法2,是直接实现接口实现的,看起来就知道简单多了:

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

通过设置 addViewController 都可以讲访问的路径指定到 setViewName 的页面中,这些页面一般配置在templates的模板包下。

自己可以实践一下看看。

posted @   碎冰  阅读(1256)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示