Spring load a file

252 views Asked by At

I need to load a file from within a directory in the root of a WAR using Spring This is the directory structure

rootOfWar
--static-dir
---- my-file.css
--WEB-INF
---- classes
.....

It is a normal WAR.

In a Spring @RestController I need to be able to read and write to my-file.css file. What is the best way to get the File, ServletContextResource or?

More Details
- The location of the file is out of my control I cannot move the file.
- The jee container is Tomcat.
- The Spring version is current 4.1.6
- The Spring environment is not using XML only annotations with WebApplicationInitializer, WebMvcConfigurerAdapter and an annotation configuration class.

Is there another way to do this like specify a file as a resource in the configuration so that it is loaded by the frame work and accessible within the application?

Basically I have JEE knowledge but my Spring knowledge on best practices concerning read/write are lacking.

1

There are 1 answers

3
Marged On

If you need to modify a file you should not make it part of the WAR. Store it somewhere outside the web package and reference it there. Everything else will lead to problems, especially when you deploy to Websphere which is often run in a restricted environment where writes are rejected.

But I consider overwriting files in the web path bad design, because you are likely to run into caching issues. Better write a servlet that generates the CSS you need. If you would be able to name the content that should overwrite your css file, you are also able to render this dynamically.

Something like this may be already sufficient:

@RequestMapping(value = "/my.css", produces = "text/css;charset=UTF-8")
public String showCss() {
    return "<here goes your css>";
}

(This is written from my memory and not tested).

The good thing is that you can modify the css any time you want and even set caching information as needed.