LiamMalone LiamMalone - 6 months ago 45
CSS Question

Accessing static resources in Spring Boot when url is not root

Sorry if this has already been asked before but everything I have tried has not worked. The problem I have is that my static resources are not being loaded when the url is not root, i.e if the url is localhost:8080/users the css files load fine but if I try load the css files for localhost:8080/users/1 or any other url after users the static files don't load. My static files are in resources/static/public/css.

I know it's probably something stupid. Thanks in advance.

My webConfig class:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/webjars/**").permitAll();
http
.authorizeRequests()
.antMatchers("/",
"/home",
"/error",
"/signup",
"/forgot-password",
"/reset-password/*",
"/public/**").permitAll()
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
//.defaultSuccessUrl()
.permitAll().and()
.rememberMe().key(rememberMeKey).rememberMeServices(rememberMeServices()).and()
.logout()
.permitAll();
}


MvcConfig class

@Configuration
@ComponentScan
public class MvcConfig extends WebMvcConfigurerAdapter {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
registry.addViewController("/login").setViewName("login");

}

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };

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


Updated ***
Header file

<link rel="shortcut icon" type="image/png" sizes="16x16" href="./public/images/favicon/logo.png"/>
<link type="text/css" rel="stylesheet" href="./public/css/style.css"/>


Footer:

<script src="./public/lib/bootstrap-3.1.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="./public/js/home.js"></script>
<script src="./public/js/webcam.js"></script>
<script src="./public/js/recordVideo.js"></script>

Answer

You are serving your static assets from file relative (./) paths. They become inaccessible when you serve files from deeper in your directory structure.

Use site relative paths: (/). Eg:

" /public/..."

Our embed a complete url to your server.

Comments