Skip to content

Instantly share code, notes, and snippets.

@ankushs92
Last active April 12, 2024 12:23
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ankushs92/0e97e070401a1bb5fe55 to your computer and use it in GitHub Desktop.
Save ankushs92/0e97e070401a1bb5fe55 to your computer and use it in GitHub Desktop.
How to get Path Variables inside a Spring interceptor.[This post assumes that you have an Interceptor registered and set up using XML or Java config]
public class SomeInterceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(final HttpServletRequest request,final HttpServletResponse response,final Object handler)
throws Exception
{
/*Assume the URI is user/{userId}/post/{postId} and our interceptor is registered for this URI.
* This map would then be a map of two elements,with keys 'userId' and 'postId'
*/
final Map<String, String> pathVariables = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
//You'll have to convert the String to Long or Integer or any other type manually. For instance..
//final Integer userId = Integer.valueOf(pathVariables.get("userId"));
//final Long postId = Long.valueOf(pathVariables.get("postId"));
}
}
@LivePwndz
Copy link

This was helpful. Thank you.

@ashokkulhari
Copy link

ashokkulhari commented May 20, 2019

Is it possible to get pathvariable with data types?

@dbrennan
Copy link

Get the Method from the handler, then use reflection to find the annotations and types of the matching parameter.

AnnotatedType[] at = method.getAnnotatedParameterTypes();
// ... code to find the param you want ...  assume n has the target index
// or you can loop through AnnotateType list matching the 
String paramName = at[n].getAnnotation(PathVariable.class).value();
Type type = at[n].getType();

@vinculum27
Copy link

Helpful - thanks!

@parmindersk
Copy link

Awesome!

@luckykumardev
Copy link

thanks :)

@gouravkrosx
Copy link

How can i get these parameters in order, as this is unordered map so it will not provide me ordered keys according to the url?
for eg: i have "http://localhost:8080/url/123/234/xyz/123" which should map to "http://localhost:8080/url/{id}/{deptId}/{code}/{empId}".
Now how can i know that first 123 maps to id or empId ???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment