2014-12-07 98 views
2

我使用的是Spring Boot,主要用于为一些静态内容提供一些基本的附加功能。用java配置在spring启动时的欢迎文件

最近我总算默认/视图映射到我的index.html通过以下方式:

@Configuration 
@EnableAutoConfiguration 
@EnableWebMvc 
@ComponentScan 
public class WebStarter extends WebMvcConfigurerAdapter { 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/app/shared/**").addResourceLocations("classpath:/www/app/shared/"); 
    } 


    @Override 
    public void addViewControllers(ViewControllerRegistry registry) { 
     registry.addViewController("/").setViewName("index.html"); 
    } 

    public static void main(String[] args) throws Exception { 
     run(WebStarter.class, args); 
    } 
} 

现在我没有能够解决这个问题,我不明白为什么。我只是收到以下异常:

javax.servlet.ServletException: Could not resolve view with name 'index.html' in servlet with name 'dispatcherServlet'

也许是某种与Spring引导版本的联系,因为我最近改变它。或者有没有其他的方式来映射默认视图?

回答

0

嗯,我解决了它。不确定是否coreect,但至少它工作。只需添加我自己的资源解析器并注册它。

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/").addResourceLocations("classpath:/www/").resourceChain(true).addResolver(new CustomResourceResolver("/", "/index.html")); 
} 

与分解:

public class CustomResourceResolver implements ResourceResolver { 

private String requestPath; 

private String resource; 

public CustomResourceResolver(String requestPath, String resource) { 
    this.requestPath = requestPath; 
    this.resource = resource; 
} 

@Override 
public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) { 

    if (!this.requestPath.equals(requestPath)) { 
     return null; 
    } 

    try { 

     for (Resource location : locations) { 
      File file = new File(location.getFile(), resource); 
      if (file.exists()) { 
       return new FileSystemResource(file); 
      } 
     } 

     return null; 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

@Override 
public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) { 
    return null; 
}