Last active
April 12, 2024 12:23
-
-
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]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} | |
} | |
Helpful - thanks!
Awesome!
thanks :)
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
Get the Method from the handler, then use reflection to find the annotations and types of the matching parameter.