Vjeetje
Vjeetje

Reputation: 5384

reference a css file in deployed webapp

I have deployed a webapp at localhost:8080/Project with Project being the context name. The webapp correctly redirects the user to the index.jsp.

But the css file in this index.jsp is not found (Error 404).

Index.jsp contains this reference:

<html lang="en">
<head>
    <link href="../css/style.css" rel="stylesheet">
</head>
</html>

My project has the following structure in the WEB-INF folder:

WEB-INF/views/index.jsp
WEB-INF/css/style.css

I also tried to directly call the css file via url localhost:8080/Project/css/style.css but this didn't work as well.


I relocated the css folder one level up (on the same level as WEB-INF) as suggested. The problem still persists. Do I have to exclude the urls starting with /css in this @Controller? Or maybe I'm on a wrong path...

@Controller
@RequestMapping("/")
public class IndexController {

    @RequestMapping(method = RequestMethod.GET)
    public String sayHello(ModelMap model) {
        return "index";
    }
}

Upvotes: 4

Views: 6799

Answers (2)

Eric Guan
Eric Guan

Reputation: 15990

WEB-INF is a private folder that is inaccessible by URL, but is accessible through the servlets Java code. You should put your html,css,js in the same folder level that the WEB-INF folder is in. That is, put them adjacent to WEB-INF, and not inside.

So a typical webapp folder will look like

*Name of webapp*
  |-js
     |-index.js
  |-css
     |-style.css
  |-index.html
  |-WEB-INF
     |-private files...

Then try

<link href="css/style.css" rel="stylesheet">

Upvotes: 1

wero
wero

Reputation: 32980

The browser loaded localhost:8080/Project and then continues to load ../css/style.css relative to that URL, therefore trying to load localhost:8080/css/style.css which apparently does not work.

You should not place web resources like CSS, JS and images under /WEB-INF since they cannot be accessed from that location. Instead use something like

WEB-INF/views/index.jsp
css/style.css

and in the JSP write

<link href="css/style.css" rel="stylesheet">

Upvotes: 5

Related Questions