Incorporate JavaScript files from the filesystem into a Spring Boot JAR application alongside Thymeleaf

I have a special utility built using spring boot with an embedded tomcat packaged into an executable jar. I am trying to include some js (or maybe json) files in the same directory as the jar file and insert them into the thymeleaf template. For example:

<script type="text/javascript" src="somepath/myfile.js"></script>

Here is what I have achieved so far: In the controller:

String userDirectory = System.getProperty("user.dir");
model.addAttribute("userDir", "file://"+userDirectory+"/");

In the template:

<script type="text/javascript" th:src="${userDir + 'myfile.js'}"></script>

Currently, I can see the code inside myfile.js via Firebug's HTML view, but it does not show up in the scripts tab, and the script is not executed (any variables defined in this file are undefined).

How can I make this work?

I am aware that I could create a json file and process it through Java, but if there is a simpler and more convenient solution available, I would prefer that. Additionally, this way I can use custom javascript instead of just json.

I understand that this approach may be risky in many scenarios, but in this particular case, security is not a concern as the application does not need to be safe from any potential injections via these files.

Answer №1

If you want to customize the WebMvcConfigurationAdapter to include a file system folder in the resource registry, you can do so by creating a CustomWebMvcConfigurerAdapter as shown below:

@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        if (resources != null) {
            registry.addResourceHandler("/myresources/**").addResourceLocations("file:" + resources);
        }
        super.addResourceHandlers(registry);
    }

}

Make sure to provide the --resources parameter when running the jar file. Remember to include a trailing / in the path.

java -jar your_jar_file --resources=/path/to/resources/

Keep in mind that the resources from this path will be registered against the /myresources/ path, so adjust your template accordingly:

<script type="text/javascript" src="myresources/myfile.js"></script>

The myfile.js file should be present in the path specified by the --resources parameter.

Update #1 (Not tested but worth a try)

I recently discovered that spring boot allows customization of static locations using a property. Refer to the Spring Common Properties Appendix for more information.

The property to define in application.properties is:

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

Add your custom locations to the above list. You can also use file resources like this:

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:/tmp/resources

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining values from a JSON String in Android: A comprehensive guide

In my Android application, I am currently working with a JSON string that looks like this: [{"tel1":"999","tel2":"0790000000","tel3":"","interval":"60","deleteLocal":"1","id":"2"}] Can someone guide me on how to efficiently parse this JSON string into a ...

Update the div each time the MySQL table is refreshed

My website functions as a messaging application that currently refreshes every 500ms by reading the outputs of the refresh.php file. I'm looking to explore the possibility of triggering the refresh function only when the 'messages' table upd ...

Creating a pop-up window in Shiny that activates when switching tabs

Is there a way to create a popover/tooltip in a Shiny app that automatically appears when users switch to a specific tab containing a data table? I have tried using the shinybs package to create a popover that shows on click or hover, but I need it to appe ...

What is the best way to display an HTTP response in a dialog box using AngularJS?

Is there a way to display the response received from the back-end in a dialog box? Once the user clicks "OK," they will be redirected to the home page, similar to how alerts work. For example, when updating employee information and receiving details like ...

The continuous progression of code execution

Having a background in Java, I decided to dive into learning Angular2 recently and have been working on it. However, I encountered a confusing situation in one of my projects that I could not figure out. For the pagination feature I was implementing, I ne ...

The input-group-btn is positioned to the right of the field, appearing to float

The input-group-btn for the targetDate field remains fixed on the right side of the input group despite screen width variations until I introduce the automatically generated CSS from the hottowel generator. I require assistance in identifying which aspect ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

Challenges with custom geometry rotation in Three.js

Recently, I've delved into Javascript and started exploring three.js. I created a custom Geometry to form a triangular prism, which looks correct initially. However, upon rotation, some of the faces appear distorted. Interestingly, the pre-built geome ...

scala regular expressions stackoverflow

Using Scala to perform pattern matching with a regular expression to extract the value of the id field val str = """<path sodipodi:nodetypes="csszsscsscssssscssssscc" inkscape:connector-curvature="0" id="basarbre" d="M 111.11111,111.11111 C 101.11111,1 ...

Python nose test encountering issues with JSON response validation

Below is the code snippet from ReportRunner class found in report_runner.py within my Flask-Restful application: class ReportRunner(object): def __init__(self): pass def setup_routes(self, app): app.add_url_rule("/run_report", view_fun ...

What is the best way to create a regular expression that can detect a string containing a full stop ('.') in the middle and ending with a comma?

string input= "devname=B399601569,devid=B39601569,logid=000013,type=traffic,srcip=192.168.192.123,srcport=2072,dstip=10.180.1.105,dstport=3206" I attempted the following expression: Pattern p = Pattern.compile("(srcip=)(\\d+)((.*)?)(dstip=)(&bs ...

Conceal a specific div element using jQuery hide method based on its unique

I'm facing a challenge with this code snippet. I am dynamically generating elements on a webpage from an array: $cars = array("Volvo", "BMW", "Toyota"); foreach($cars as $item) { echo '<div class="column col-3" id="'.$item.'" ...

Interact with a LinkButton using JavaScript on Internet Explorer 9

My Repeater contains multiple LinkButtons that perform a postback when manually clicked. However, my attempts to trigger the click event on a LinkButton using JavaScript have been unsuccessful. I have tried both OnClick and OnCommand without any luck. Lin ...

Modify the css to style the identical listview

Currently, I have an application (jQuery mobile 1.4.3) that contains a List View where I'm dynamically populating the list using AJAX. The challenge I am facing is that I want to adjust the CSS so that certain elements like buttons and left side space ...

Unable to fetch value in a separate class using Android Volley

public class CustomStringRequest { String requestUrl; String requestBody; String responseValue; public CustomStringRequest(String url, String body){ this.requestUrl = url; this.requestBody = body; responseValue = "" ...

creating objects dynamically through URL

Attempting to dynamically create a new instance of a mongoose model through a URL request using Express. In the example below, when const kind = 'modelOne' is received via the URL, I encounter an error stating 'Cannot read property 'mo ...

Scroll down navigation bar hide on scroll offset

Is there a way to prevent the navigation menu from disappearing on iOS when scrolling down due to the 'bounce' effect at the top of the page? Perhaps setting an offset for triggering the script or is there another solution? var prev = 0; var $win ...

Root location for offline and pre-production in the Backbone boilerplate router

I am currently utilizing the backbone boilerplate found at https://github.com/tbranyen/backbone-boilerplate My development process involves working on static HTML/JS files offline and conducting tests offline before deploying them to another site for pre- ...

Add data from a dynamic table into the database

Currently, I am attempting to extract the values from a dynamically generated table and input them into a database. Here's what I have at the moment: The JavaScript function below successfully adds all values to the table when called upon by a button ...

Using soapUI to extract information from a JSON Response with arrays

After receiving a JSON response from a previous test step in soapUI, I am working on parsing the information using a groovy script. Here's a snippet of the JSON response: { "AccountClosed": false, "AccountId": 86270, "AccountNumber": "2915", ...