0
votes

I'm trying to load static resources such as css files and javascript files in my jsp files using relative paths, but it seems by servlet mappings are overriding the mapping to them.

Project structure:

webapp/
   assets/
      scripts/
         dashboard.js
      styles/
         common.css
   WEB-INF/
      views/
         pages/
            home/
               body.jsp

web.xml:

...
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

...

mvc-dispatcher-servlet.xml:

    <import resource="applicationContext.xml" />
<context:component-scan base-package="com.nickythorne.controller" />

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/>
</bean>

<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer" >
    <property name="definitions" value="/WEB-INF/tiles-definitions.xml" />
</bean>

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

I my JSP file where i'm trying to load the stylesheet:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}" />

<link rel="stylesheet" type="text/css" href="<c:url value='/assets/styles/common.css'/>" />

The error I get is:

WARN org.springframework.web.servlet.PageNotFound:1108 - No mapping found for HTTP request with URI [/project/assets/styles/common.css] in DispatcherServlet with name 'mvc-dispatcher'

1

1 Answers

0
votes

The better approach is:

<c:set var="root" value="${pageContext.request.contextPath}"/>

<link rel="stylesheet" type="text/css" href="${root}/assets/styles/common.css"/>

${root} will be resolved into your relative context path regardless of ports, protocol, domain name etc.