Alejandro
Alejandro

Reputation: 1

How to serve static files from a Spring component project in a JAR, within a main project that depends on it?

I have two projects in Spring. One is a library of reusable components, which has static files (CSS, JS). The other project is the main application, where I need to serve these static files. By "serve", I mean being able to access the JS files from the components project. I've packaged them into a JAR file, but when I try to use the component "control-tipos.js", the path is not being resolved. enter image description here enter image description here

I tried using dependencies, and it can detect the classes but not the static files (JS, CSS).

Upvotes: 0

Views: 139

Answers (2)

Drew Harvey
Drew Harvey

Reputation: 166

Based on your screenshot I'm assuming you're using the Vaadin Framework.

Location of Files in Addon Project:

The "addon" project must have its static files placed in the correct directory (you've already done this correctly). In the "addon" project, the resources should be placed in:

src/main/resources/META-INF/resources/frontend

Accessing Files in Main Project:

In the main project, accessing the files from your addon project's jar will differ depending on where you are accessing them (from your frontend files or your Java files).

From a Frontend View:

Replace META-INF/resources/frontend with Frontend/generated/jar-resources/. So the path to your control-tipos.js file would be Frontend/generated/jar-resources/componentes/controltipos/control-tipos.js.

Example:

// import your control-tipos file from a frontend view 
// for example: src/main/frontend/views/main-view.tsx

import "Frontend/generated/jar-resources/componentes/controltipos/control-tipos.js";
// or
import {controlComponent} from "Frontend/generated/jar-resources/componentes/controltipos/control-tipos.js";


export default function MainView() {
  ....
}

From a Java View:

Replace META-INF/resources/frontend with ./. So the path to your control-tipos.js file would be ./componentes/controltipos/control-tipos.js.

Example:

@JsModule("./componentes/controltipos/control-tipos.js")
public class MainView extends VerticalLayout {
  ...
}

You can refer to the documentation for loading resources to understand the correct paths to use for the resources: Loading Resources.

Upvotes: 0

If you already provided the right dependency to ensure communication between the two project then make sure to (mvn clean install) and then check if your files are included in (BOOT-INF/classes/static) if so , try calling your html page ofcourse dont forget to add your javascript file

<script src="/js/script.js"></script> 

to your html file.

please note sometimes spring boot doesn't recognise the static folder so make sure to create the folder and files structure correctly.

you can read about it here : https://www.baeldung.com/spring-mvc-static-resources

Upvotes: 0

Related Questions