使用上下文路径时,我在Spring Boot中遇到静态内容问题。即:我希望将我的应用部署到localhost:8080/{appname}/
当我运行没有上下文路径的应用程序时,一切正常,Spring Boot找到并运行我的.html
文件(来自resources / templates /,我正在使用Thymeleaf
)和JS文件(来自资源) / static / js /)但是当我用以下任何一个添加上下文路径时:
server.context-path=/{appname}
OR
server.servlet-path=/{appname}
然后JS文件仍显示.html
页面生成 404错误。
我尝试更改spring.resources.static-locations
中的application.properties
并覆盖addResourceHandlers()
中的MvcConfig.class
方法但似乎无法正常工作
我使用的是MvcConfig
课程,因为我需要定义CookieLocaleResolver
和MessageSource
,但这就是MvcConfig
中的全部内容。我不使用@EnableWebMvc
,只使用@SpringBootApplication
@ComponentScan
注释。
任何帮助将不胜感激:)
答案 0 :(得分:3)
根据你的评论:
HTML引用了没有应用程序上下文的JS
问题不在于Spring服务js,而是页面没有正确创建资源的URL。
Thymeleaf提供了一种机制,只需使用th
前缀标记src属性即可自动支持此功能。
请参阅第2节和第34页;与上下文相关的网址":www.thymeleaf.org/doc/articles/standardurlsyntax.html
答案 1 :(得分:1)
下面的示例显示了如何在Spring Boot中配置静态资源。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**/*.js").addResourceLocations("/ui/static/");
registry.addResourceHandler("/**/*.css").addResourceLocations("/ui/static/");
}
}
路径模式
添加一个资源处理程序,用于根据指定的URL路径模式提供静态资源。对于与指定路径模式之一匹配的每个传入请求,将调用该处理程序。
允许使用“ / static / ”或“ / css / {文件名:\ w + \。css}”}之类的样式。 有关语法的更多详细信息,请参见** org.springframework.util.AntPathMatcher 。
您的jsp / html外观参考静态内容,如下所示
<link href="/webAppContext/cssa/bootstrap.min.css" rel="stylesheet"/>
<script src="/webAppContext/jquery-2.2.1.min.js"></script>
<script src="/webAppContext/bootstrap.min.js"></script>
使用哪个浏览器尝试获取静态内容的网址
http://localhost:8080/webAppContext/jquery-2.2.1.min.js
http://localhost:8080/webAppContext/bootstrap.min.js
http://localhost:8080/webAppContext/cssa/bootstrap.min.css
server.servlet.context-path=/webAppContext is in your application.properties
答案 2 :(得分:-2)
我的配置是:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
public static final Logger LOG = LoggerFactory.getLogger(MvcConfig.class);
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setCookieName("language");
cookieLocaleResolver.setCookieMaxAge(-1);
cookieLocaleResolver.setDefaultLocale(Locale.FRENCH);
return cookieLocaleResolver;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/lang");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new Urli18nRewriterInterceptor());
}
}
和文件夹结构: