春季启动提供了即插即用型的设施,是春天启动的美。这里同样适用于在带有弹簧引导的Web应用程序中的位置提供静态内容。默认情况下,春季启动从类路径默认属性提供静态资源:
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
和默认的静态路径模式是:
spring.mvc.static-path-pattern=/**
但它是很好的做法不是默认以提供其他。
但是,spring引导还可以通过编程实现WebMvcConfigurerAdapter
来定制该配置。
@EnableAutoConfiguration
public class AddCustomLocations {
@Bean
WebMvcConfigurer configurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").
addResourceLocations("classpath:/my-custom-location/");
}
};
}
public static void main (String[] args) {
SpringApplication app =
new SpringApplication(AddCustomLocations.class);
app.run(args);
}
}
现在添加新的静态内容像src/main/resources/new-custom-location/page1.js
当像http://localhost:8080/pages/page1.js
URL模式找到,那么将page1.js担任静态资源。
现在为templates/HelloWorld.html
,则需要默认属性修改(假设文件夹templates
已经存在):在目录/templates/
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html
相应的HTML页面将通过视图解析器呈现。
编辑答案:
如果您正在使用@EnableWebMvc
则只是将其删除。你的问题应该得到解决。 如果仍然没有解决问题,则覆盖addViewControllers(ViewControllerRegistry registry)
类的方法WebMvcConfigurerAdapter
,正如我们在前面的代码中所做的那样。在addResourceHandlers (ResourceHandlerRegistry registry)
方法之后,在上面的代码中添加以下代码片段。
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/test").setViewName("testPage");
}
前缀/templates/
和后缀.html
将由视图解析器加入。
使用这个,我可以解决我的js和css和图像,但是当我在你的springboot和appliction中使用html。我无法访问index.html。显示javax.servlet。ServletException:无法使用名称为“dispatcherServlet”的名称为'index'的servlet解析视图。但是当我将.html更改为ftl时。一切都好。请告诉为什么如果你知道。谢谢 – Ezreal
@Ezreal,我认为FreeMarker配置在你的类路径上,所以如果存在,就从类路径中删除依赖项。现在,第二件事是你没有提供你的实际代码index.html,我们可以提供任何更新,即使我按照我的理解提供解决方案。请参阅我编辑的答案。 –