DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Java Virtual Threads and Scaling
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring 3 WebMVC - Optional Path Variables

Spring 3 WebMVC - Optional Path Variables

By 
Sebastian Herold user avatar
Sebastian Herold
·
Oct. 19, 10 · Interview
Likes (1)
Comment
Save
Tweet
Share
51.4K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

To bind requests to controller methods via request pattern, Spring WebMVC's REST-feature is a perfect choice. Take a request like http://example.domain/houses/213234 and you can easily bind it to a controller method via annotation and bind path variables:

...

@RequestMapping("/houses/{id}")
public String handleHouse(@PathVariable long id) {
return "viewHouse";
}

Problem

But the problem was, I needed optional path segments small and preview. That means, it would like to handle requests like /houses/preview/small/213234, /houses/small/213234, /houses/preview/213234 and the original /houses/213234. Why can't I use only one @RequestMapping for that.

Ok, I could introduce three new methods with request mappings:

...

@RequestMapping("/houses/{id}")
public String handleHouse(@PathVariable long id) {
return "viewHouse";
}

@RequestMapping("/houses/preview/{id}")
...

@RequestMapping("/houses/preview/small/{id}")
...

@RequestMapping("/houses/small/{id}")
...

But imagine I have 3 or 4 optional path segments. I would had 8 or 16 methods to handle all request. So, there must be another option.

Browsing through the source code, I found an org.springframework.util.AntPathMatcher which is reponsable for parsing the request uri and extract variables. It seems to be the right place for an extension.

Here is, how I would like to write my handler method:

@RequestMapping("/houses/[preview/][small/]{id}")
public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) {
return "view";
}

Solution

Let's do the extension:

package de.herold.spring3;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.AntPathMatcher;

/**
* Extends {@link AntPathMatcher} to introduce the feature of optional path
* variables. It's supports request mappings like:
*
* <pre>
* @RequestMapping("/houses/[preview/][small/]{id}")
* public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) {
* ...
* }
* </pre>
*
*/
public class OptionalPathMatcher extends AntPathMatcher {

public static final String ESCAPE_BEGIN = "[";
public static final String ESCAPE_END = "]";

/**
* stores a request mapping pattern and corresponding variable
* configuration.
*/
protected static class PatternVariant {

private final String pattern;
private Map variables;

public Map getVariables() {
return variables;
}

public PatternVariant(String pattern) {
super();
this.pattern = pattern;
}

public PatternVariant(PatternVariant parent, int startPos, int endPos, boolean include) {
final String p = parent.getPattern();
final String varName = p.substring(startPos + 1, endPos);
this.pattern = p.substring(0, startPos) + (include ? varName : "") + p.substring(endPos + 1);

this.variables = new HashMap();
if (parent.getVariables() != null) {
this.variables.putAll(parent.getVariables());
}
this.variables.put(varName, Boolean.toString(include));
}

public String getPattern() {
return pattern;
}
}

/**
* here we use {@link AntPathMatcher#doMatch(String, String, boolean, Map)}
* to do the real match against the
* {@link #getPatternVariants(PatternVariant) calculated patters}. If
* needed, template variables are set.
*/
@Override
protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) {
for (PatternVariant patternVariant : getPatternVariants(new PatternVariant(pattern))) {
if (super.doMatch(patternVariant.getPattern(), path, fullMatch, uriTemplateVariables)) {
if (uriTemplateVariables != null && patternVariant.getVariables() != null) {
uriTemplateVariables.putAll(patternVariant.getVariables());
}
return true;
}
}

return false;
}

/**
* build recursicly all possible request pattern for the given request
* pattern. For pattern: /houses/[preview/][small/]{id}, it
* generates all combinations: /houses/preview/small/{id},
* /houses/preview/{id} /houses/small/{id}
* /houses/{id}
*/
protected PatternVariant[] getPatternVariants(PatternVariant variant) {
final String pattern = variant.getPattern();
if (!pattern.contains(ESCAPE_BEGIN)) {
return new PatternVariant[] { variant };
} else {
int startPos = pattern.indexOf(ESCAPE_BEGIN);
int endPos = pattern.indexOf(ESCAPE_END, startPos + 1);
PatternVariant[] withOptionalParam = getPatternVariants(new PatternVariant(variant, startPos, endPos, true));
PatternVariant[] withOutOptionalParam = getPatternVariants(new PatternVariant(variant, startPos, endPos, false));
return concat(withOptionalParam, withOutOptionalParam);
}
}

/**
* utility function for array concatenation
*/
private static PatternVariant[] concat(PatternVariant[] A, PatternVariant[] B) {
PatternVariant[] C = new PatternVariant[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
}

Now let Spring use our new path matcher. Here you have the Spring application context:

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

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="pathMatcher">
<bean class="de.herold.webapp.spring3.OptionalPathMatcher" />
</property>
</bean>
<context:component-scan base-package="de.herold" />
</beans>

That's it. Just set the pathMatcher property of AnnotationMethodHandlerAdapter.

Fazit

I know this implementation is far from being elegant or effective. My intention was to show an extension of the AntPathMatcher. Maybe someone gets inspired and provides an extension to handle pattern like:

@RequestMapping("/houses/{**}/{id}")
public String handleHouse(@PathVariable long id, @PathVariable("**") String inBetween) {
return "viewHouse";
}

to get the "**" as a concrete value.

The sources for a little prove of concept are attached.

Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!