Akhil K Nambiar
Akhil K Nambiar

Reputation: 3975

Spring MVC Resources not mapping

Following is my mvc-dispatcher.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/view/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:annotation-driven />
<mvc:resources location="/static/" mapping="/static/**" />
<context:component-scan base-package="in.codejava.personal.controllers" />
</beans>

Where am I going wrong? All static/* url's is being mapped by a 404 Controller that I created instead of the static resources.

WEB.XML

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<display-name>Personal Web Blogs</display-name>
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<!--    <servlet-mapping> -->
<!--        <servlet-name>default</servlet-name> -->
<!--        <url-pattern>/static/*</url-pattern> -->
<!--    </servlet-mapping> -->
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

If I remove the commented section it works properly.

Upvotes: 1

Views: 8428

Answers (2)

angel.lopezrial
angel.lopezrial

Reputation: 99

I just add a new servlet mapping in my web.xml <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping>

and then make reference to the resources path on my html:

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

Upvotes: 0

nickdos
nickdos

Reputation: 8414

I'm going to take a punt and assume you are using a conventional directory structure for your JS, CSS, images resources, like this:

  • src/main/webapp/[js|css|images]

In this case your mvc:resources should look like:

<mvc:resources mapping="/static/**" location="/" />

and you should reference them in your JSPs something like this: "${pageContext.request.contextPath}/static/js/foo.js"

Upvotes: 5

Related Questions