Spring Web MVC @PathVariable with Regular Expressions

This tutorial will show you how we use @PathVariable annotation with Regular Expressions in Spring Web MVC. Sometimes you need more precision in defining URI template variables. The @RequestMapping and @GetMapping annotations support the use of regular expressions in URI template variables. The syntax is {varName:regex} where the first part defines the variable name and the second – the regular expression.

For example, with @RequestMapping:

@RequestMapping("/spring-web/{fileName:[a-z-]+}-{version:\d\.\d\.\d}{extension:\.[a-z]+}")
public void handle(@PathVariable String fileName, @PathVariable String version, @PathVariable String extension) {
	// ...
}

Or with @GetMapping annotation:

@GetMapping("/spring-web/{fileName:[a-z-]+}-{version:\d\.\d\.\d}{extension:\.[a-z]+}")
public void handle(@PathVariable String fileName, @PathVariable String version, @PathVariable String extension) {
	// ...
}

Prerequisites

Java at least 8, Gradle 6.5.1, Maven 3.6.3, Spring Boot 2.3.3, Thymeleaf Template

Project Setup

You can create either gradle or maven based project in your favorite IDE or tool. The name of the project is spring-mvc-path-variable-regex.

If you are creating gradle based project then use below build.gradle script:

buildscript {
	ext {
		springBootVersion = '2.3.3.RELEASE'
	}
	
    repositories {
    	mavenCentral()
    }
    
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
	implementation "org.springframework.boot:spring-boot-starter-web:${springBootVersion}"
	implementation("org.springframework.boot:spring-boot-starter-thymeleaf:${springBootVersion}")
}

If you are creating maven based project then use below pom.xml file:

<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.roytuts</groupId>
	<artifactId>spring-mvc-path-variable-regex</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.3.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Spring Controller Class

I am going to create below Spring controller class that will handle incoming request and outgoing response.

Notice in the below regular expression path how I defined two path variables with regular expression.

package com.roytuts.spring.mvc.path.variable.regex.controller;

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

@Controller
public class HelloWorldController {

	@GetMapping("hello/{fileName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
	public String helloWorld(@PathVariable String fileName, @PathVariable String version,
			@PathVariable String extension, Model model) {
		model.addAttribute("fileName", fileName + version + extension);
		
		return "hello";
	}

}

View File – UI

The following view file displays the value of path variable regular expression value when rendered in the browser. This template file – hello.html – is kept under src/main/resources/templates folder.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring MVC Path Variable</title>
</head>
<body>
	<p>
		 Path Variable with regular expression Value : <strong th:text="${fileName}"></strong>
	</p>
</body>
</html>

Main Class

A class having main method with @SpringBootApplication is enough to deploy the application into embedded Tomcat server.

package com.roytuts.spring.mvc.path.variable.regex;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringPathVariableRegexApp {

	public static void main(String[] args) {
		SpringApplication.run(SpringPathVariableRegexApp.class, args);
	}

}

Testing the Application

Now hit the URL http://localhost:8080/hello/spring-web-mvc-5.2.8.jar in the browser, you will see the below output in the browser:

spring mvc path variable with regular expression

Source Code

Download

Thanks for reading.

Leave a Reply

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