Search code examples
vaadin

How create a link pointing to a static HTML-page?


In my Vaadin application (I am using Vaadin v24.3.8) I am trying to define me a “help”-link that should serve a static HTML help-page.

The file help.html to be served is placed in folder <resources>/help/. To make spring-boot serve that static file I added a configuration class providing access to a resource folder "help" using the URL-path "help/...":

...  package and imports omitted ...
 
@Configuration
public class StaticConfig implements WebMvcConfigurer
{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
            .addResourceHandler("/help/*.*")          // URL-path: …/help/…
            .addResourceLocations("classpath:/help/") // → serves content from …/src/main/resources/help
            ;
    }
}

If I enter the URL "https://localhost:8085/help/help.html" that file gets properly served - as expected.

Next I defined myself a link (i.e. a Vaadin "anchor") in my application’s main-view like so:

Anchor help = new Anchor("help/help.html", "Help"); 
...
addToNavBar(help);

The link is displayed fine. The URL that is shown when I hover with the mouse over it is: "https://localhost:8085/help/help.html".

If I inspect the element in the browser's development tools it shows:

   <a class="help-link" href="help/help.html">Help</a>

again: everything as expected.

However, when I click onto that link I get the error:

Could not navigate to 'help/help.html'
Available routes:
<root>
login
logout

This detailed message is only shown when running in development mode.

The URL shown in the browser's address field at that point is "https://localhost:8085/help/help.html".

If I then trigger a refresh in the browser, i.e. if I reload that page it loads the help-page without problem.

?!? Why is that page not loaded immediately when I click the link in the application? Why do I first get an error and only on reload the page loads fine? What am I missing here???


Solution

  • If you don't specifically need a Spring resource handler for this file, you can just put it in /src/main/resources/META-INF/resources/help/help.html (see https://vaadin.com/docs/latest/flow/advanced/loading-resources#flow.resource-cheat-sheet) and have Vaadin serve it as a static resource instead.

    By default, the static resource is available for authenticated users; use HttpSecurity to specify different rules: https://vaadin.com/docs/latest/flow/security/enabling-security#security-configuration-class