Spring Boot Static Resources From Controllers and Other Classes

I've been trying to solve this issue and I can't find the answer.

I've been having to use src/main/resources/public/whatever... in order to access static resources from class files. I was under the impression that if you use /static /public /resources... that Spring Boot already has those paths configured.

I'm lost at this point and not sure how I can access these files without having to prepend src/main/resources/public.

EDIT

Based on the suggestions regarding the static content, I created a private directory to protect files etc... that I don't want publicly available. And left css, images, etc... in the /public folder.

Thank you all for the suggestions and recommendations, I appreciate it!

Answers


After more searching I ran across an example that used the ClassLoader. I've only been using Spring for a short time and not aware of all the tools that are available, there might be a better way than this; if so please tell let me know.

ClassLoader classLoader = getClass().getClassLoader()
new File(classLoader.getResource('public/file-name-or-directory').getFile())

So far it looks like it's working, I need to do some further testing and will post back if any issues.


The directories you list, /static, /public and /resources, are for static content that will be served up by a web-application. Things like javascript files and images that will always be the same no matter who requests them and when, as opposed to JSPs for example that need to be processed on the server per request.

If you need to access a configured property in one of your Java classes (it must be a Spring bean), then you can put it in your application.properties file, and have Spring inject it using the @Value annotation.

Example code from Spring docs:

import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

Spring Boot expect you to use for content served directly src/main/resources/static

and to use for templating src/main/resources/templates


Need Your Help

Adding new row to multicolumn listview

android android-layout listview android-listview

I am new to android and in my application i have a multi column listview and i need to add new row or item to listview on button click..i try a lot of solutions from here and also from a lot of web...

IIS AppPool error (1013 - W3SVC)

iis coldfusion iis-6

We're getting a number of warnings in the Application Event Viewer on our IIS installation. We have an AppPool set up which contains two websites (both ColdFusion sites, not .NET).