首页 > 解决方案 > 资源未在带有 Java 配置的 Spring MVC 中加载

问题描述

首先我在RootConfig中使用了WebMvcConfigurerAdapter,并且资源已经连接,但是我没有部署Spring Security项目。

@Configuration
@ComponentScan({"org.example"})
public class RootConfig extends WebMvcConfigurerAdapter {
}

然后我从 RootConfig 类中删除了 WebMvcConfigurerAdapter,项目变得可部署,但资源停止工作。

@Configuration
@ComponentScan({"org.example"})
public class RootConfig {
}

项目结构

我如何连接样式:

<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/index.css">

我的资源处理程序:

@Configuration
@EnableWebMvc
@ComponentScan({
        "org.example",
        "org.example.model",
        "org.example.repo",
        "org.example.service"
})
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

SpringMvcDispatcherServletInitializer:

public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

标签: javaspringsecuritymodel-view-controllerresources

解决方案


尝试在以下资源上使用 web-security 覆盖配置方法,如果您使用的是 thymleaf,请使用 @ 表示 URI href="@{/**/css/index.css}"或正确检查路径。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/*");
}

推荐阅读