Recently, I’m working on a project in which I use Grails to implement RESTful API back-end with the “rest-api” profile. It’s simple and works well, until the frond-end developer asks me to intergrate the front-end implementation(React with “javscript/css/font/image”) files into the back-end Grails project.
The problems are:
How to expose the static resources(“javscript/css/font/image” files) in a Grails project to make it available directly to the browser without the controller handling?
How to integrate the “index.html” of the React application into Grails?
It tooks me several hours to find the answers. Here is the solutions.
Solution for problem 1
First, put the static resources files(including “index.html”) into the “src/main/webapp/” directory. After doing so, when packaging the Grails project into “war” file, the content in the “src/main/webapp/” directory will be packaged into the “war” file under the root path.
Second, in the “UrlMappings.groovy” under the “controllers” directory, add the following content to declare the static resources are NOT handled by controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
According to the Grail official document, after the 2 steps above, the static resources should be available for the browser. However it did not. The following steps took me a lot of time to find out from here.
- Update the “conf/application.yml” by adding the following content:
1 2 3
Without this configuration Grails exposes all the static resources under the “/static/” path, with the configuration the static resources will be exposed under the “/” path, which is what we want.
Solution for problem 2
- Create a new controller
1 2 3 4 5
- Route the “/” path to the new controller
1 2 3 4 5 6 7 8 9 10 11 12
Then when you access the root path of the web application, the “index.html” content will be returned.
I tried to make the “index.html” as part of the static resources to make it available, but then I found it’s not a good idea, the reasons are:
The URL of root domain cannot be redirected to “index.html”, which means “http://test.com” is not available but only “http://test.com/index.html” is;
Even if using “http://test.com/index.html”, after some content on the page is changed, refreshing does not work since the “index.html” is treated as “static resource” which means it’s cached in the browser.
So the “index.html” content must be handled as danymic content by controller.