美文网首页
SpringBoot 2.0设置默认访问页

SpringBoot 2.0设置默认访问页

作者: 知道越多不知道越多 | 来源:发表于2019-05-24 14:17 被阅读0次

每个网站都需要一个默认访问的页面,方面用户访问,因此我们需要给我们的平台设置一个默认访问的URL。

我使用的是SpringBoot 2.0版本,2.0版本是将页面存放在/resources/public/ 目录下,其他静态资源(js,css,img...)存放在/resources/statis/下,我们需要指定默认访问public下的一个html。

接下来我们来实现

新增一个class类,继承WebMvcConfigurerAdapter,代码如下:

@Configuration
public class DefaultController extends WebMvcConfigurerAdapter{
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/blog/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

以上代码添加一个/路径的controller,转发到/blog/index.html页面,当然/blog/index.html是在/public/下存放;DefaultController 需要添加@Configuration注解,且该类下的包一定要被Spring扫描到,否者无法注入到IOC里。
项目启动,访问http://localhsot:8080 即可看到你想要的页面。

SpringBoot 2.0版本已经启用WebMvcConfigurerAdapter类

/** @deprecated */
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
}

以上代码我们可以看到WebMvcConfigurerAdapter 被@Deprecated注解,表示弃用,那它的替代者是什么呢?我们该如何实现?
从类的定义我们还能看出它实现了WebMvcConfigurer 接口,所以我们直接实现WebMvcConfigurer 接口,然后重写addViewControllers方法即可。

@Configuration
public class WebConfigurer implements WebMvcConfigurer{
   @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/blog/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}

重启服务,访问http://localhsot:8080 即可看到你想要的页面。

相关文章

网友评论

      本文标题:SpringBoot 2.0设置默认访问页

      本文链接:https://www.haomeiwen.com/subject/qgygzqtx.html