Spring 4 MVC Static Resource Mapping Example (Include JS, Css and Images)

By Yashwant Chavan, Views 86758, Date 02-Jan-2017

In this tutorial, You will learn how to serve static resources such as IMAGES, JS and CSS files from specific locations using Spring 4 MVC.

tags spring

Spring 4 Eclipse project set up

Spring 4 MVC Static Resource Mapping Example - Eclipse project setup

Tools and Technologies

  1. Apache Maven 3.0.4
  2. JDK 1.8
  3. Spring 4.1.4.RELEASE

pom.xml

As we are using Maven project. Let's define the spring 4 specific maven dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>Spring4Examples</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>Spring4Examples</name>
    <description></description>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <spring.version>4.1.4.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>
</project>

Spring 4 Application Configuration

@EnableWebMvc annotation is used to enable Spring MVC.

@Configuration annotation imports the Spring configuration. @Configuration objects are managed as Spring beans within the container, imported configurations are used to injected using @Autowired or @Inject.

@ComponentScan is equivalent to <context:component-scan base-package="..." used to lookup the beans and components classes in the spring context.

Configure static resources handlers - Add handlers to serve static resources such as images, js and css files from specific locations.

Override addResourceHandlers(ResourceHandlerRegistry registry) method. This handlers used to serve static resources such as images, js, and css files from specific locations.

addResourceHandler() - Add a resource handler for serving static resources based on the specified URL path patterns.

addResourceLocations() - Add one or more resource locations from which to serve static content. Each location must point to a valid directory. Multiple locations may be specified as a comma-separated list, and the locations will be checked for a given resource in the order specified.

package com.technicalkeeda.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages = "com.technicalkeeda")
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    }

}

WebApplicationInitializer Configuration

Earlier we used to define web.xml to declare the dispatcher related configurations. Now we are using 100% code base (annotation and java config ) approach to doing the application configuration.

WebApplicationInitializer interface is implemented using Servlet 3.0+ style, Which is used to configure the ServletContext programmatically rather than traditional web.xml-based approach.

package com.technicalkeeda.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class ApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(ApplicationConfig.class);
        ctx.setServletContext(container);

        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}

Default Page (index.jsp)

Create index.jsp page, Which is default view of the Spring 4 MVC application.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Spring 4 MVC - File Upload Example</title>
        <link type="text/css" href="<c:url value='/assets/css/bootstrap.min.css' />" rel="stylesheet" />
        <script src="<c:url value='/assets/js/app.js' />" type="text/javascript"></script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>Spring 4 MVC - Static Resource Mapping</h1>
                    <img src="<c:url value='/assets/img/teady.jpg' />" alt="..." class="img-thumbnail">
                    <hr>
                    <a href="#" class="btn btn-primary" role="button" onclick="message()">Click Me</a>
                </div>
            </div>
        </div>
    </body>
</html>

app.js

add message() function, Which will display the alert message.

function message() {
    alert("hello!!!");
}

Deploy and Execute

Enter URI (http://localhost:8080/Spring4Examples) in your browser, It will render the index.jsp page.

Spring 4 MVC Static Resource Mapping Example Default View
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com