我使用Spring Boot主要是为一些静态内容提供一些基本的附加功能。
最近,我以某种方式设法通过以下方式将默认/视图映射到我的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 Boot版本有某种联系,因为我最近在改变它。或者还有其他方法如何映射默认视图?
答案 0 :(得分: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;
}