Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get request URL in Spring Boot RestController

I am trying to get the request URL in a RestController. The RestController has multiple methods annotated with @RequestMapping for different URIs and I am wondering how I can get the absolute URL from the @RequestMapping annotations.

@RestController @RequestMapping(value = "/my/absolute/url/{urlid}/tests" public class Test {    @ResponseBody    @RequestMapping(value "/",produces = "application/json")    public String getURLValue(){       //get URL value here which should be in this case, for instance if urlid              //is 1 in request then  "/my/absolute/url/1/tests"       String test = getURL ?       return test;    } }  
like image 229
NRA Avatar asked Jun 08 '16 18:06

NRA


People also ask

Which of the following annotations will help us to read the value from the request URL?

We can use @RequestMapping with @RequestParam annotation to retrieve the URL parameter and map it to the method argument.

What is @RestController in spring boot?

Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody . This annotation is applied to a class to mark it as a request handler. Spring RestController annotation is used to create RESTful web services using Spring MVC.


1 Answers

You may try adding an additional argument of type HttpServletRequest to the getUrlValue() method:

@RequestMapping(value ="/",produces = "application/json") public String getURLValue(HttpServletRequest request){     String test = request.getRequestURI();     return test; } 
like image 121
Deepak Avatar answered Oct 05 '22 22:10

Deepak