场景:渲染引擎
若采用渲染引擎,JSP等VIEW渲染技术,可以通过addViewController的方式解决。
配置文件方式 ```java @Configuration public class DefaultView extends WebMvcConfigurerAdapter {
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(“/Blog”).setViewName(“forward:index.jsp”); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(registry); }
}
- **控制器配置方式**```java@Controller@RequestMapping("/")public class IndexController {@RequestMapping("/Blog")public String index() {return "forward:index.html";}}
场景:前后端分离
若完全采用前后端分离的模式,即前端所有资源都放在addresourceHandler配置的路径下。
@Configurationpublic class WebMVCConfig extends WebMvcConfigurationSupport {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/static/");registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler(new String[] { "/static/images/**" });super.addResourceHandlers(registry);}}
此时不能通过配置addViewController的方式解决,会抛出异常:“javax.servlet.ServletException: Could not resolve view with name ‘forward:/index.html’ in servlet with name ‘dispatcherServlet’”。只能通过response.redirect(“index.html”)的方式重指向默认主页。
@Controllerpublic class DefaultController {@RequestMapping("/")public void index(HttpServletResponse response) throws IOException {response.sendRedirect("index.html");}@RequestMapping(value = "/{[path:[^\\.]*}")public void other(HttpServletResponse response) throws IOException {response.sendRedirect("index.html");}}
参考
脚本之家:SpringBoot设置默认主页的方法步骤
https://www.jb51.net/article/202536.htm
