I want to configure Spring MVC to serve dynamic files mixed with static files, like this (URL => File):
/iAmDynamic.html => /WEB-INF/views/iAmDynamic.html.ftl
/iAmAlsoDynamic.js => /WEB-INF/views/iAmAlsoDynamic.js.ftl
/iAmStatiHtml => /iAmStatic.html
The DispatchServlet
is mapped to /
, annotation-based MVC configuration is enabled and I have a view controller like this (Simplified):
@Controller
public class ViewController
{
@RequestMapping("*.html")
public String handleHtml(final HttpServletRequest request)
{
return request.getServletPath();
}
@RequestMapping("*.js")
public String handleJavaScript(final HttpServletRequest request)
{
return request.getServletPath();
}
}
The spring config looks like this:
<context:component-scan base-package="myPackage" />
<mvc:default-servlet-handler />
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
</bean>
Unfortunately it doesn't work. When this <mvc:default-servlet-handler />
is active then I can only access the iAmStatic.html
file. When I disable the default-servlet-handler then only the dynamic stuff works. But I want both at once and that's exactly what this default-servlet-handler should do, or not? Where is the error here?
I had similar problem, none of the requests were getting mapped to the Spring Controllers: I discovered I was missing this in spring config xml:
<mvc:annotation-driven/>
It seems with , this is necessary. From documentation, the purpose of doing this is:
Configures the annotation-driven Spring MVC Controller programming model
I will also let DefaultServlet handle static content requests.
So your spring config should look like:
<context:component-scan base-package="myPackage" />
<!-- Define location and mapping of static content -->
<mvc:resources location="/static/" mapping="/static/**"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven/>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
</bean>
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With