怎么在Springboot中設置默認訪問路徑?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
搜過很多博客,里面的內容雖然可以用。但是基本上都是基于繼承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 別忘了加,我自己就是忘了加,以為沒生效,折騰半天。
@Controller public class PageController { @GetMapping(value = "/") public String defaultPath(Model model) { return "hello"; } }
看完上述內容,你們掌握怎么在Springboot中設置默認訪問路徑的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。