arash moeen arash moeen - 22 days ago 5
HTML Question

Spring dynamic url access to css/js files

I have a simple Spring boot application. There URL that would be used here is going to be like:

sub.domain.com/variable1/variable2


and variable1 and variable2 can be anything for example:

sub.domain.com/kfc/foo
sub.domain.com/subway/boo


and I capture those in my controller as below:

@Controller
public class IndexController {

@RequestMapping(value="/{var1}/{var2}", method = RequestMethod.GET)
public String Index(@PathVariable(value="var1") String variable1, @PathVariable(value="var2") String variable2) {
return "/index.html";
}
}


which will redirect to my html page which is located at
src/main/webapp/index.html


so the index page is loaded under the dynamic url but then none of the scrips or stylesheets are found because it's trying to find them under variable1 path.

for example if I have

sub.domain.com/kfc/foo


and my link to css in the index.html is

<link rel="stylesheet" href="styles/index.css" />


it will try to find the index.css under

sub.domain.com/kfc/styles/index.css


how can I tell the app to look into the right place for the styles or js files?

Answer

index.html is trying to load styles from a relative path.

In order for index.html to load styles under sub.domain.com/styles/index.css, add a / in link tag **/**styles/index.css <link rel="stylesheet" href="/styles/index.css" />