In this tutorial I will show you how to define Spring optional path variable (PathVariable) in REST service. Here I will use Java 8’s java.util.Optional and at least Spring 4.1 to support optional PathVariable.

Prerequisites

Java 8, Spring 4

Maven Dependency

Here in the below pom.xml file we have added the required dependencies such as Java, spring and jackson for json.

We have also added a property failOnMissingWebXml to avoid validation failure if deployment descriptor web.xml file is missing.

Generally when you work on annotation based spring mvc application and you don’t want to create web.xml file then you need to add this property in the pom.xml file.

<properties>
	<failOnMissingWebXml>false</failOnMissingWebXml>
	<java-version>1.8</java-version>
	<spring.version>4.3.1.RELEASE</spring.version>
	<jackson.version>2.8.6</jackson.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>${jackson.version}</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>3.0.1</version>
		<scope>provided</scope>
	</dependency>
</dependencies>

Create below config class in order to enable annotation based Spring MVC and scan the REST Controller classes from package jeejava.controllers

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "jeejava.controllers")
public class AppConfig {

}

Create below class in order to load Dispatcher Servlet and other initialization configurations.

Here I have included class AppConfig in the method getRootConfigClasses() to enable annotation based Spring MVC and scan the controller classes from the package jeejava.controllers.

I have defined Servlet mapping as root (“/”) in the method getServletMapping().

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

}

Create below REST Controller class that will handle end-user’s request and response.

In the below method getHello() I have passed an argument with Java 8’s new feature java.util.Optional to make the parameter optional.

Notice there are two endpoints for RequestMapping because when you do not pass any value for PathVaribale name then simply putting URI /hello in http request will not work and you will get 404 – Resource Not Found in the browser.

So in order to let http request know that when you do not pass any value for PathVariable name then map URI to /hello instead of /hello/{name}.

Notice how we have passed spring optional path variable in the REST method for data type String.

import java.util.Optional;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringRestController {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = { "/hello/{name}", "/hello" }, method = RequestMethod.GET)
	public ResponseEntity getHello(@PathVariable Optional<String> name) {

		return new ResponseEntity("Hi " + (name.isPresent() ? name.get() : "Anonymous") + ", Good Morning!",
				HttpStatus.OK);
	}

}

Check outputs in browsers for below URLs for the example spring optional path variable.

spring optional path variable

spring optional path variable

spring optional path variable

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 *