Spring Boot not loading static resources it depend

2020-05-06 04:56发布

问题:

I have problem to load the file under static folder on spring boot application.

The problem is RequestMapping depth more than 2 like @RequestMapping("spring/xyz")

The @RequestMapping("spring") single depth works well but 2 depth is prefixed 'spring' it is connect localhost:8080/spring/'static folder'

I found half solution here

my folder structure is:

static/css/some.css  
static/templates/velocity.vm

case 1: works well

java:
    @RequestMapping("spring")

html:
    <link rel="stylesheet" href="css/some.css">

case2: works well

java:
    @RequestMapping("spring/xyz")

html:
    <link rel="stylesheet" href="../css/some.css">

case3: not working

java:
    @RequestMapping("spring/xyz/123")

html:
    <link rel="stylesheet" href="../css/some.css">

it is called 'http//localhost/spring/xyz/css/some.css'

case3: works well

java:
    @RequestMapping("spring/xyz/123")

html:
    <link rel="stylesheet" href="../../css/some.css">

case4: works well

java:
    @RequestMapping("123")

html:
    <link rel="stylesheet" href="../../css/some.css">

It works!! even if I use ../../ relative path. I don't know why this works.

Actually I didn't understand Spring Boot API well that I consider use ViewResoler something load other static resources.

I want to know this load path machanism and how to the RequestMapping url path link to call the 'http//localhost/spring/xyz/css/some.css'

I appriciate any answer thanks~!!

I refer to the same issue on spring.io here from 'metalhead' and 'Brian Clozel'

回答1:

if you are using thymeleaf you can also specify the path as :

<link rel="stylesheet" th:href="@{/css/main.css}"
href="../static/css/main.css" />

it worked properly for me for any depth.