Sunday, 4 November 2012

Serving Static Resources With Spring MVC

This post explains how to server static content from a Spring MVC web application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Serving-Static-Resources directory.

JSP Page

We keep only the main index.jsp page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="" %>
<!doctype html>
<html lang="en">
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
  <script type="text/javascript"
    src="<c:url value='/resources/js/SomeJavascript.js'/>">
  <title>Welcome To Spring Serving Static Resources !!!</title>
    <h1>Spring - Serving Static Resources !!!</h1>
    <img border="0"
      src="<c:url value='/resources/img/MyArt.png'/>" alt="My Art" />
Regarding static resources:
  • We link JQuery from Google's CDN.
  • We link our own SomeJavascript.js and make sure the URL is properly constructed.
  • In the body, we add an image.


Spring Project Structure For Resources
In the Spring project itself, we put all the resources under a separate resources directory which does not stand under WEB-INF.
  • Images are stored under /resources/img.
  • Javascript is storted under /resources/js.
Our Javascript is a simple pop-up messages displayed when the HTML document is loaded:
$(document).ready(function() {
    alert("JS loaded successfully!");

Web Configuration & Controller

We need to modify our web configuration to add a static resource handler and configure it by specifying where to fetch these:
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {


    public void addResourceHandlers(ResourceHandlerRegistry registry) {


We also simplify our controller:
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";


Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:


The image and the pop-up will be displayed:

More Spring related posts here.

No comments:

Post a comment