By Leon


2012-09-03 14:24:53 8 Comments

In Spring MVC controller, I can get path variable using @PathVariable to get the value of a variable defined in @RequestMapping. How can I get the value of the variable in an interceptor?

Thank you very much!

3 comments

@ashario 2014-05-05 08:52:27

The thread linked to by Pao worked a treat for me

In the preHandle() method you can extract the various PathVariables by running the following code

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 

@spiderman 2015-06-18 21:37:12

and then String value= (String) pathVariables.get("yourPathVarName"); that's it. This should be marked as answer

@Andreas 2016-04-08 05:55:56

Perfect, the example code also works with @ControllerAdvice and @ExceptionHandler. Thanks

@Philippe 2017-01-17 19:19:56

Why isn't this marked as the correct answer?!

@Basil Battikhi 2019-03-12 15:02:20

should be marked as accepted answer

@freakman 2013-08-06 14:04:18

Almost 1 year too late, but:

         String[] requestMappingParams = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).params()

         for (String value : requestMappingParams) {...

should help

@chrismarx 2015-05-28 15:53:11

this appears useful for retrieving the RequestParams but I don't see how to get the value of the PathVariables with this approach

@Pao 2012-09-03 15:44:18

There is a thread in the Spring forums, where someone says, there is no "easy way", so i suppose you would have to parse the URL to get it.

@Philippe 2017-01-17 21:13:34

Actually the answer by @ashario above (stackoverflow.com/a/23468496/35274) shows that it can be done.

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] Spring MVC - How to get all request params in a map in Spring controller?

16 Answered Questions

[SOLVED] Spring MVC @PathVariable getting truncated

2 Answered Questions

3 Answered Questions

14 Answered Questions

[SOLVED] Spring MVC @PathVariable with dot (.) is getting truncated

5 Answered Questions

5 Answered Questions

1 Answered Questions

Spring MVC INterceptor is not being called

2 Answered Questions

0 Answered Questions

Spring MVC: How to get the remaining path after the controller path?

Sponsored Content