lets-blade / blade

:rocket: Lightning fast and elegant mvc framework for Java8
https://lets-blade.github.io
Apache License 2.0
5.85k stars 1.17k forks source link

Static HTML resources not working #410

Closed franckvallee closed 4 years ago

franckvallee commented 4 years ago

On route "/", I send back an HTML file containing style and script local resources. e.g.

file jquery.min.js is placed under current resources directory /src/main/resources/local/script/jquery.min.js

But declaring addStatics( "/local"), or replacing the directory name by static won't allow to load the static resources.

To workaround this, I had to write the kind of code below: Blade.of() .get("/", ctx -> ctx.html(output.toString())) .get("/local/:dir/:file", (RouteContext ctx) -> { String resourceName = String.format("static/%s/%s", ctx.pathString("dir"), ctx.pathString("file")); File resourceFile; URL resource = BasicHTTPServiceTest.class.getClassLoader().getResource(resourceName); if (resource == null) { System.err.println(resourceName + " is not found!"); return; } System.err.println("Resource found at " + resource.toString()); resourceFile = new File(resource.getFile()); ctx.body(new ByteBody(resourceFile)); // String resourceContent = Files.readString( (new File(resource.getFile())).toPath(), StandardCharsets.US_ASCII); switch (ctx.pathString("dir")) { case "script": ctx.contentType( "text/javascript; charset=UTF-8"); break; case "style": ctx.contentType( "text/css; charset=UTF-8"); } }) .start();

I think I miss something somewhere or there's a more elegant way to achieve it, or there's a real bug in the code.

To Reproduce

Steps to reproduce the behavior:

  1. Operating system and its version
  2. Build tools gradle
  3. JDK 11 Blade 2.0.15.RELEASE
  4. See error => javascript and css styles are not loading From the subproject GUI auropim.zip auropim.zip

    in attachment, run the class org.auropim.gui.BasicHTTPServiceNotWorkingTest. Call /localhost:9000 from your favorite browser.

Expected behavior:

Blade should behave as a HTTP server by redistributing internal static resources.

franckvallee commented 4 years ago

By debugging I found that StaticFileHandler.getGradleResourcesDirectory() is returning as directory: [project root]\build\classes\java\resources. But gradle doesn't move my resources directory in here... I will try to understand how gradle should manage this correctly.

franckvallee commented 4 years ago

The workaround consist in simply adding this line in the gradle.build file: sourceSets { // force resources to be moved under build/classes/java main { output.setResourcesDir("$buildDir/classes/java/resources") } }