My JSP pages in my dynamic web application (in Eclipse) are not being styled by my CSS code. I have included a stylesheet in index.jsp as follows:
index.jsp
<html>
<head>
<title>To Do List - Home</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stylesheet.css">
</head>
<body>
<a href="tasks">Tasks</a>
</body>
</html>
And my project structure is as follows:
I thought that href="${pageContext.request.contextPath}/css/stylesheet.css
would look for stylesheet.css
in ToDoList/WebContent/css/
. If I try navigating directly to the stylesheet in the browser via http://localhost:8080/ToDoList/css/stylesheet.css
it returns a 404 error.
I am aware this question has been asked before but from looking at the other questions I still can't figure out what is wrong with my project structure.
Update:
So I added <mvc:resources mapping="/css/**" location="/css/" />
to my servlet config, but now when I navigate to any page other than index.jsp I get a 404 error.
todolist-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Scan for JavaConfig, annotated with @Configuration -->
<context:component-scan base-package="com.petehallw.todolist.main" />
<context:annotation-config/>
<mvc:resources mapping="/css/**" location="/css/" />
<!-- Configure Spring view resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
The error I get is:
WARNING: No mapping found for HTTP request with URI [/ToDoList/tasks] in DispatcherServlet with name 'todolist'
This is upon clicking a link to "tasks" in index.jsp which was previously returning the tasks.jsp page.
For every URL in the app, you can make use of c:url
tag in JSTL
lib.
<a href="<c:url value="/tasks"/>">Tasks</a>.
So, if you have controller method mapping @requestmapping("/tasks"), it will be invoked.
Or try as <a href="${pageContext.request.contextPath}/tasks">Tasks</a>
like you use at css files.
Important: You should add <mvc:annotation-driven />
in xml configuration for the support of annotation-driven MVC controllers like @RequestMapping
, @Controller
.