2016-06-08 1363 views
12

我想在RestController中获取请求URL。 RestController有多个方法用@RequestMapping为不同的URI注释,我想知道如何从@RequestMapping注释中获得绝对URL。如何在Spring Boot RestController中获取请求URL

@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; 
    } 
} 

回答

22

您可以尝试添加HttpServletRequest类型的附加参数传递给getUrlValue()方法:

@RequestMapping(value ="/",produces = "application/json") 
public String getURLValue(HttpServletRequest request){ 
    String test = request.getRequestURI(); 
    return test; 
} 
+0

感谢您的回复和示例。我知道这种方法,但想知道是否有办法使用控制器级别的任何属性获取url信息,但似乎这是正确的方式。 – NRA

+0

HttpServletRequest从哪里导入? –

+0

javax.servlet.http.HttpServletRequest – Deepak

2

允许让你的系统,而不仅仅是当前的任何URL。

import org.springframework.hateoas.mvc.ControllerLinkBuilder 
... 
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId)) 

URI methodUri = linkBuilder.Uri() 
String methodUrl = methodUri.getPath() 
-1
@RestController 
@RequestMapping(value = "/my/absolute/url/{urlid}/tests") 
public class AndroidAppController { 

    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String getURLValue(@PathVariable("urlid") String urlid) { 
     String getURL = urlid; 
     return getURL; 
    } 

} 
相关问题