1

I have a rest controller with @GetMapping annotation for mapping HTTP requests onto specific handler methods:

@RestController
class Handler(){
    @GetMapping(path = ["method"])
    fun handlerMethod(){
        //...
    }
}

Also I have email service where I need to send some email with link to my endpoint (in that case http://host/method)

@Service
class EmailService(val config: Config){

    fun sendEmail(){
        // send "config.baseUrl/${getMethodPath()}"
    }

    fun getMethodPath(){
        //todo
    }
}

Here I get base url from configuration (http://host). Is there any way to get path attribute in EmailService from Handler's @GetMapping for build link to my service?

grolegor
  • 1,260
  • 1
  • 16
  • 22
  • Maybe this would be of some help: https://stackoverflow.com/questions/12710307/spring-mvc-request-mapping-can-this-be-dynamic-configurable – Andronicus Mar 13 '19 at 17:12

3 Answers3

1

you can get the request bound to the current thread by RequestContextHolder.

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

The above code will get the HttpServletRequest and then you can use [HttpServletRequest#getPathInfo()][1] to get the path of the URL

Prateek Jain
  • 1,504
  • 4
  • 17
  • 27
0

You can get the path information from HttpServletRequest object. Please check this:

How to get request URL in Spring Boot RestController

If you are not getting exact path, check this for different approaches to get paths:
What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

A Baldino
  • 178
  • 1
  • 11
0

Spring has support for doing just this task. In your controller method, pass a parameter of type UriComponentsBuilder. This builder will have all the information about the current request routing (hostname, port, path, etc.). You can then use MvcUriComponentsBuilder to have Spring construct the link that you need (Java, but it should be equivalent in Kotlin):

MvcUriComponentsBuilder.relativeTo(builderParameter)
    .fromMethod(Handler.class, "method")
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152