Home > Software design >  Resources are not loaded in Spring MVC with Java config
Resources are not loaded in Spring MVC with Java config

Time:10-26

Firstly I was used WebMvcConfigurerAdapter in RootConfig, and the resources were connected, but I didn't deploy the Spring Security project.

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

Then I deleted WebMvcConfigurerAdapter from the class RootConfig, and the project became deployable, but the resources stopped working.

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

project structure

How I connect styles:

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

My resource handler:

@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[]{"/"};
    }
}

CodePudding user response:

Use this syntex to access your css file <link href="<c:url value="/resources/css/index.css />" rel="stylesheet">

CodePudding user response:

try to override config method with web-security on resources like below and also if you are using thymleaf use @ to represent URI href="@{/**/css/index.css}" or else check the path properly.

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