2

Is there a way to get the registered URL pattern (In Controller) from the incoming HTTP request.

For Example, If my controller code is

@RestController
@RequestMapping("greeting")
public class Greeting {

    @GetMapping("/{text}")
    public String echo(@PathVariable("text") String text) {
        return text;
    }

}

Incoming request is http://localhost:8080/greeting/Hello, I want to get the mapping value /greeting/{text}. Can I achieve the same using any Interceptor or Handler?

I have registered all the original mapping URLs like /greeting/{text}, /users/find/{id} etc., and want to perform some validation if the incoming request falls into any of those registered requests. I could have achieve the same using one custom method level annotation but I don't want to change all the codes now. It would be nice if I can achieve the same from a single Interceptor or extending any spring handlers.

The above snippet is a sample one. I have 4 to 5 spring applications with different apis and want create a common security package which can achieve the same.

Soumya Tripathy
  • 31
  • 1
  • 1
  • 5
  • Just out of curiosity, why would you need that? `/greeting/Hello` not enough? – cosmos Jun 11 '18 at 15:51
  • I have one requirement where I have registered all the controllers URLs like **/greeting/{text}** in the database and I want to perform some validation, if the incoming request matches the same. I can do it in each method level, but It would be better if can have the logic in one place so that I can reuse it across projects. – Soumya Tripathy Jun 11 '18 at 18:57

2 Answers2

4

You can access this from

final String pattern = request.getAttribute(org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE):

Source: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerMapping.html#BEST_MATCHING_PATTERN_ATTRIBUTE

Morten Haraldsen
  • 1,013
  • 12
  • 24
0

HttpServletRequest request request.getCurrentUrl() can get the url

Selenium
  • 55
  • 6