Spring Web MVC @PathVariable

This tutorial will show you how to use @PathVariable annotation in Spring MVC. The @PathVariable annotation is used on a method argument to bind it to the value of a URI template variable. You can also make this path variable optional in the URI. path variable can appear in any path segment of the URI.

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.

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</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.

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

import java.time.LocalDateTime;

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/{msg}")
	public String helloWorld(@PathVariable String msg, Model model) {
		model.addAttribute("today", LocalDateTime.now());
		model.addAttribute("msg", msg);

		return "hello";
	}

}

To process the @PathVariable annotation, Spring MVC needs to find the matching URI template variable by name. You can specify it in the annotation:

@GetMapping("/hello/{msg}")
	public String helloWorld(@PathVariable("msg") String msg, Model model) {
    ...
}

Or if the URI template variable name matches the method argument name you can omit that detail. As long as your code is not compiled without debugging information, Spring MVC will match the method argument name to the URI template variable name:

@GetMapping("/hello/{msg}")
	public String helloWorld(@PathVariable String msg, Model model) {
    ...
}

View File – UI

The following view file displays the value of path variable’s 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's Value : <strong th:text="${today}"></strong>, <strong th:text="${msg}"></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;

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

@SpringBootApplication
public class SpringMvcPathVariableApp {

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

}

Testing the Application

Now hit the URL http://localhost:8080/hello/Good%20Evening in the browser, you will see the below output in the browser:

spring mvc path variable

Source Code

Download

Thanks for reading.

Leave a Reply

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