我正在迁移到Spring5,我正在将我所有的xml迁移到java config,但是我被固定在静态资源上。
在我的旧xml配置中,我有这样定义的资源:<mvc:resources mapping="/3rdparty/**" location="/3rdparty/" />
我正在将它们添加到我的Java Config类
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.mypackages.*")
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/3rdparty/**").addResourceLocations("/3rdparty/");
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/");
bean.setSuffix(".jsp");
return bean;
}
}现在我在我的资源No mapping for GET /myapp/gui/3rdparty/bootstrap-3.3.6-dist/js/bootstrap.min.js中得到了这些错误
这一切都与xml配置一起工作得很好。你知道我该如何定义这个模式吗..
文件夹结构如下所示
ROOT
|_WEB-INF
|_META-INF
|_gui
|_3rdparty我还将我的启动转移到了java config。
public class AppInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.mypackages.config");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container
.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}提前感谢您的帮助
发布于 2019-09-25 23:50:13
我建议改变两件事:
AnnotationConfigWebApplicationContext#scan("com.mypackages.config")而不是#setConfigLocation(...)来扫描带有@Configuration注释的类。或者直接注册一个特定的类:#register(WebConfig.class).#addResourceLocations("/3rdparty/")中检查参数。您的文件夹结构表明#addResourceLocations("/gui/3rdparty/")可能会起作用。在打包为.war的Maven项目中,所有web资源通常都位于单独的webapp文件夹中,请参阅Maven War Plugin for reference。在您的案例中:
|-- pom.xml
|-- src
|-- main
|-- java
| |-- com
| |-- mypackages
| |-- config
| |-- WebConfig.java
| |-- AppInitializer.java
|-- resources
|-- webapp
|-- gui
|-- 3rdparty
|-- bootstrap.min.js使用WebConfig.java
@ComponentScan(basePackages = "com.stackoverflow.*")
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/gui/3rdparty/**").addResourceLocations("/gui/3rdparty/");
}
}和AppInitializer.java
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebConfig.class);
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}}
引导程序资源将在http://<host>:<port>/gui/3rdparty/bootstrap.min.js上提供
https://stackoverflow.com/questions/58084732
复制相似问题