Question

I put index.jsp inside WEB-INF. Then I have a servlet which dispatch request to that file.

@WebServlet(name="Home", urlPatterns={"/"})
public class Home extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
    }
}

I have a css folder which is outside the WEB-INF folder. It contains the css.css file.

The This is the content of index.jsp file:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="<c:url value="/css/css.css" />" rel="stylesheet">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

The content of css file:

body {
    color: red;
}

Question: Why doesn't the sentence "Hello World" turn red? Why can't the index.jsp file access the css file?

Was it helpful?

Solution

It looks like you are mapping your servlet "Home" for all incoming requests. So when the browser makes a request for the css url, it is intercepted by the servlet and it is unable to find it. You can change the servlet mapping for the home servlet so that it does not intercept all requests

@WebServlet(name="Home", urlPatterns={"/home"})

OTHER TIPS

Add following in your jsp

   <link rel="stylesheet" type="text/css" href="/project-context-root-name/css/myfile.css"/>

If it did not work further then do below step.

In your web.xml file add following

  <servlet-mapping>
  <servlet-name>servlet-name</servlet-name>
  <url-pattern>/css/*</url-pattern>
  </servlet-mapping>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top