场景:渲染引擎

若采用渲染引擎,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); }

}

  1. - **控制器配置方式**
  2. ```java
  3. @Controller
  4. @RequestMapping("/")
  5. public class IndexController {
  6. @RequestMapping("/Blog")
  7. public String index() {
  8. return "forward:index.html";
  9. }
  10. }

场景:前后端分离

若完全采用前后端分离的模式,即前端所有资源都放在addresourceHandler配置的路径下。

  1. @Configuration
  2. public class WebMVCConfig extends WebMvcConfigurationSupport {
  3. @Override
  4. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  5. registry.addResourceHandler("/static/**")
  6. .addResourceLocations("classpath:/static/static/");
  7. registry.addResourceHandler("/**")
  8. .addResourceLocations("classpath:/static/");
  9. registry.addResourceHandler(new String[] { "/static/images/**" });
  10. super.addResourceHandlers(registry);
  11. }
  12. }

此时不能通过配置addViewController的方式解决,会抛出异常:“javax.servlet.ServletException: Could not resolve view with name ‘forward:/index.html’ in servlet with name ‘dispatcherServlet’”。只能通过response.redirect(“index.html”)的方式重指向默认主页。

  1. @Controller
  2. public class DefaultController {
  3. @RequestMapping("/")
  4. public void index(HttpServletResponse response) throws IOException {
  5. response.sendRedirect("index.html");
  6. }
  7. @RequestMapping(value = "/{[path:[^\\.]*}")
  8. public void other(HttpServletResponse response) throws IOException {
  9. response.sendRedirect("index.html");
  10. }
  11. }

参考

脚本之家:SpringBoot设置默认主页的方法步骤
https://www.jb51.net/article/202536.htm