Green Fireman
Green Fireman

Reputation: 697

JSP doesn't see CSS

I'm trying to make a simple Servlets + JSP project. It's structure looks like this:

enter image description here

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>App</title>
  <link rel="stylesheet" type="text/css" href="../css/style.css"/>
</head>
<body>
<h1>Header</h1>
</body>
</html>

style.css:

body {
    background-color: beige;
}

web.xml:

<web-app>
    <display-name>App</display-name>

    <servlet>
        <servlet-name>IndexServlet</servlet-name>
        <servlet-class>com.example.web.IndexServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>IndexServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

When I start the application and open it in the browser I see the index.jsp page but it's background is white so the css isn't working there. What could be the problem?

Upvotes: 1

Views: 11590

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

There are two problems in your app:

  1. In JSP, you should use ${pageContext.request.contextPath} to append the base path for your URLs. With this, you can be sure you will use absolute path instead of relative path for your URLs. So, this:

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

    Will be

    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css"/>
    

    This can also be accomplished by using <c:url> from JSTL:

    <link rel="stylesheet" type="text/css" href="<c:url value='/css/style.css' />"/>
    
  2. Your servlet is mapping to every request made in your app. Note that this includes simple requests for resources like this CSS file. If you're not handling these requests successfully, you may get an error response or an empty response or whatever, depends on how you handle the request for CSS files in the servlet. I recommend you to change the URL pattern for your servlet to map to specific paths instead.

    <servlet-mapping>
        <servlet-name>IndexServlet</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>
    

Upvotes: 5

Related Questions