1

I am running a webapp in a Tomcat 7 container, and am recieving 404 errors when attempting to access static content (.css, etc.). Below is my directory structure:

  • ROOT
    • META-INF
    • resources
      • css
    • WEB-INF
      • classes
      • lib

I have defined a default servlet in my deployment descriptor as follows:

<servlet>
    <servlet-name>HomeController</servlet-name>
    <servlet-class>controller.HomeController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HomeController</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

The HomeController servlet forwards the request to a .jsp, and the view is rendered properly.

request.getRequestDispatcher("view.jsp").forward(request,
        response);

"view.jsp" has a link to a stylesheet (style.css) located in the css folder listed above. However, because the servlet is configured as a default servlet, I am now not able to access the static content in the css folder, and any request for this stylesheet returns a 404 error.

<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/style.css" />

Is there any way around this? What is the best method for serving up static resources, but still being able to define a default servlet?

elpisu
  • 759
  • 3
  • 11
  • 18

2 Answers2

2

Don't homegrow your own default servlet. Use the servletcontainer's builtin default servlet. Your front controller should be mapped on a more specific URL pattern, e.g. *.html or /pages/*.

If your intent is to not change the URLs, then you should create an additional Filter class which is mapped on /* and just continues the chain when the /resources/* is requested and otherwise forward to the front controller servlet which is mapped on /pages/*.

E.g.

String uri = ((HttpServletRequest) request).getRequestURI();
if (uri.startsWith("/resources/")) {
    chain.doFilter(request, response); // Goes to container's default servlet.
} else {
    request.getRequestDispatcher("/pages" + uri).forward(request, response);
}

And link your CSS just with the /resources path in the URL, exactly as you have in your public webcontent folder structure.

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

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Shouldn't you be linking css from resources path like this:

<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/resources/css/style.css" />
anubhava
  • 761,203
  • 64
  • 569
  • 643