Springboot设置默认访问路径方法实现

这篇文章主要介绍了Springboot设置默认访问路径方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

当使用springboot与其他框架结合编写web前后端时,可能存在这样的需求:我想在访问10.10.10.100时,实际上需要访问10.10.10.100/hello页面。(端口已省略,自行设置)

解决

方案1 - 实现WebMvcConfigurer接口

搜过很多博客,里面的内容虽然可以用。但是基本上都是基于继承WebMvcConfigurerAdapter类实现的,而官方的源码里面已经不推荐使用该类了。

下面给出我的解决方案,很简单:

 import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class DefaultView implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("hello"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); } } 

补充&注意点

setViewName :将 / 指向 /hello

这里需要注意,因为我的项目里把url的访问路径后缀".html"全部都去掉了,所以可以这么用。如果你的不是,需要做对应调整。

补充我的application.properties文件部分配置:

 server.port=80 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.mvc.favicon.enabled=true 

@Configuration 别忘了加,我自己就是忘了加,以为没生效,折腾半天。

方案2 - @Controller路由设置

 @Controller public class PageController { @GetMapping(value = "/") public String defaultPath(Model model) { return "hello"; } } 

properties文件配置同方案1一致

到此这篇关于Springboot设置默认访问路径方法实现的文章就介绍到这了,更多相关Springboot 默认访问路径内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是Springboot设置默认访问路径方法实现的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java