0
votes

I'm developing a webapp using Spring 4.3.4 + Spring MVC + Thymeleaf 3.0.2. By the way, I've not integrated Spring Security yet so there isn't any security policy in place.

The problem is simple: the static resources are not loaded on browser (error 404).

This is my project folder structure, that is a standard maven structure (I've put static resources on /src/main/resources/static, but i also tried /src/main/webapp/ or /src/main/webapp/WEB-INF/):

enter image description here
And this is, for example, how I link CSS on my pages (trust me, the file /src/main/resources/static/assets/css/style.css really exists):

<link th:href="@{/assets/css/style.css}" type="text/css" />

As far as I know I shouldn't need a ResourceHandler to handle contents on /src/main/resourcess/static/assets/, that should already be available at /assets/, but it doesn't work, so in my spring java configuration I've also made also few tries like:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("classpath:/static/assets/**").addResourceLocations("/assets/");
    registry.addResourceHandler("classpath:/static/pages/**").addResourceLocations("/pages/");
}

In any case CSS and JS files are not accessible.

My dispatcher servlet is mapped to the root /:

<servlet-mapping>
    <servlet-name>myappDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

If I inspect HTML on browser I can see that the above tag becomes:

<link href="/myapp/assets/css/style.css" rel="stylesheet" type="text/css">

that looks pretty correct to me, right?

So, why do I receive a 404 error if I try to access the css? Am I forgetting something important?

Thank you,
Luca

2

2 Answers

1
votes

To solve the problem I needed to change my folder structure, moving static resources into /webapp/ folder. I'm pretty sure there is a way to leave CSS and JS into /resources/ folder, but I didn't make it work, so this is my new folder structure:

enter image description here

Then I've set the resource handler mapping:

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

And this is the link tag used in the HTML template (that works both for dynamic and static loading of the page):

<link th:href="@{/assets/css/style.css}" href="../../assets/css/style.css"  rel="stylesheet" type="text/css" />
0
votes

remove resource handler mappings,

then change to

<link th:href="@{/assets/css/style.css}" href="../static/assets/css/style.css" type="text/css" />