This tutorial will show you how we use @MatrixVariable annotation in Spring Web MVC. This tutorial will show you how to obtain matrix variable in a map from the URL segment. The URI has the possibility of including name-value pairs within path segments. The general “URI path parameters” could be applied although the more unique “Matrix URIs”, originating from an old post by Tim Berners-Lee, is also frequently used and fairly well known. Within Spring MVC these are referred to as matrix variables.

Matrix variables can appear in any path segment, each matrix variable separated with a “;” (semicolon). For example: “/cars;color=red;year=2012”. Multiple values may be either “,” (comma) separated “color=red,green,blue” or the variable name may be repeated “color=red;color=green;color=blue”.

If a URL is expected to contain matrix variables, the request mapping pattern must represent them with a URI template. This ensures the request can be matched correctly regardless of whether matrix variables are present or not and in what order they are provided.
All matrix variables may be obtained in a Map:

// GET /owners/42;q=11;r=12/pets/21;q=22;s=23

@RequestMapping(value = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET)
public void findPet(
        @MatrixVariable Map<String, String> matrixVars,
        @MatrixVariable(pathVar="petId"") Map<String, String> petMatrixVars) {
    // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
    // petMatrixVars: ["q" : 11, "s" : 23]
}

More info can be found in Matrix Variables section in http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/mvc.html

For this tutorial we will create maven based web project in Eclipse.

If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Prerequisites

The following configurations are required in order to run the application

Eclipse
JDK 1.7
Tomcat 7
Have maven installed and configured
Spring 4 and JSTL API dependencies in pom.xml

Now we will see the below steps how to create a maven based spring project in Eclipse

Step 1. Create a maven based web project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-webapp

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : spring

Step 2. Modify the pom.xml file as shown below.

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.roytuts</groupId>
    <artifactId>spring</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.version>1.7</jdk.version>
        <spring.version>4.1.6.RELEASE</spring.version>
    </properties>

    <dependencies>

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

        <!-- The spring-aop module provides an AOP(aspect-oriented programming)
            implementation -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- The spring-webmvc module contains Spring’s model-view-controller (MVC)
            and REST Web Services implementation for web applications -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- The spring-web module provides basic web-oriented integration features
            such as multipart file upload functionality and the initialization of the
            IoC container using Servlet listeners and a web-oriented application context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3. If you see JRE System Library[J2SE-1.4] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.4], click on Edit button and select the appropriate jdk 1.7 from the next window. Click on Finish then Ok.

Step 4. Create Spring XML configuration file controllers.xml under src/main/resources/spring directory

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- Support annotation -->
    <context:annotation-config></context:annotation-config>

    <!-- enable Matrix variable -->
    <mvc:annotation-driven enable-matrix-variables="true" />

    <!-- Scan the package where Spring Controllers are placed -->
    <context:component-scan base-package="com.roytuts.spring.controllers" />

    <!-- Resolves logical String-based view names to actual View types -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <!-- Where pages are kept -->
        <property name="prefix" value="/" />
        <!-- What is the page extension -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

Step 5. Create Controller class

package com.roytuts.spring.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

  @RequestMapping(value = "owners/{ownerId}/reports/{reportId}")
  public String findReport(@PathVariable String ownerId, @MatrixVariable Map<String, List<String>> matrixVars,
      @MatrixVariable(pathVar = "reportId") Map<String, List<String>> reportMatrixVars, Model model) {
    System.out.println("ownerId : " + ownerId);
    List<List<String>> matrixVarlist = map2List(matrixVars);
    for (List<String> list : matrixVarlist) {
      for (String string : list) {
        System.out.println(string);
      }
    }
    List<List<String>> reportMatrixVarlist = map2List(matrixVars);
    for (List<String> list : reportMatrixVarlist) {
      for (String string : list) {
        System.out.println(string);
      }
    }
    model.addAttribute("matrixVars", matrixVars);
    model.addAttribute("reportMatrixVars", reportMatrixVars);
    return "hello";
  }

  private List<List<String>> map2List(Map<String, List<String>> matrixVarMap) {
    List<List<String>> outlist = new ArrayList<List<String>>();
    Collection<Entry<String, List<String>>> matrixVarSet = matrixVarMap.entrySet();
    for (Entry<String, List<String>> entry : matrixVarSet) {
      List<String> rowList = new ArrayList<String>();
      String name = entry.getKey();
      rowList.add(name);
      List<String> matrixVar = entry.getValue();
      rowList.addAll(matrixVar);
      outlist.add(rowList);
    }
    return outlist;
  }

}

Step 6. Now modify web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>Spring MVC</display-name>

    <!-- dispatcher servlet acts as a front controller for each request/response -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- load Spring controllers while dispatcher servlet loads -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/controllers.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Step 7. Create hello.jsp file under webapp folder

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<html>
<body>
    <c:forEach items="${matrixVars}" var="entry">
       ${entry.value}<br>
    </c:forEach>
    <p />
    <c:forEach items="${reportMatrixVars}" var="entry">
       ${entry.value}<br>
    </c:forEach>
</body>
</html>

Step 8. Now run the application and hit the URL http://localhost:8080/spring/owners/42;q=11;r=12/reports/21;q=22;s=23 in the browser, you will see the below output in the browser.

spring mvc matrix variable in a map

Console Output

ownerId : 42
q
11
22
r
12
s
23
q
11
22
r
12
s
23

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *