簡體   English   中英

使用 Java 配置在 Spring MVC 中未加載資源

[英]Resources are not loaded in Spring MVC with Java config

首先我在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[]{"/"};
    }
}

嘗試使用 web-security 在如下資源上覆蓋配置方法,如果您正在使用 thymleaf,請使用 @ 來表示 URI href="@{/**/css/index.css}"或者正確檢查路徑。

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

使用此語法訪問您的 css 文件 <link href="<c:url value="/resources/css/index.css />" rel="stylesheet">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM