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;@Configurationpublic 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路由設置@Controllerpublic class PageController { @GetMapping(value = '/') public String defaultPath(Model model) { return 'hello'; } }
properties文件配置同方案1一致
到此這篇關于Springboot設置默認訪問路徑方法實現的文章就介紹到這了,更多相關Springboot 默認訪問路徑內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
