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="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/SomeJavascript.js'/>">
  </script>
  <title>Welcome To Spring Serving Static Resources !!!</title>
</head>
<body>
    <h1>Spring - Serving Static Resources !!!</h1>
    <img border="0"
      src="<c:url value='/resources/img/MyArt.png'/>" alt="My Art" />
</body>
</html>
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.

Resources

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:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

      registry
        .addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    }

}
We also simplify our controller:
@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:

  http://localhost:8585/spring-serving-static-resources/

The image and the pop-up will be displayed:



More Spring related posts here.

No comments:

Post a Comment