英文:
Log url to Spring controller from inside it
问题
假设您有一个类似于以下代码的 Spring MVC 控制器:
@Controller
public class RestController {
@GetMapping(value = "/test")
public @ResponseBody Test getTestData(...) {
// console log path to controller: http://localhost:80/app/test
return testData;
}
}
在控制器内部是否有可能从中记录/打印出 URL?在上面的示例中,输出可能类似于 https://localhost:80/app/test
。
但是,使用 servlet 的 .getRequestUrl
并不能正常工作。
英文:
Suppose you have a Spring MVC controller, something like this
@Controller
public class RestController {
@GetMapping(value = "/test")
public @ResponseBody Test getTestData(...) {
// console log path to controller: http://localhost:80/app/test
return testData;
}
}
Is it possible to log/print from inside the controller the url to it? In the example above the output would be something like https://localhost:80/app/test
Using .getRequestUrl
from the servlet is not behaving correctly.
答案1
得分: 2
You can inject UriComponentsBuilder as a parameter and then use the method toUriString(). From the documentation, it is used to build a relative URI from the current request's context. This should work as expected Doc.
@Controller
public class RestController {
...
@GetMapping(value = "/test")
public @ResponseBody Test getTestData(UriComponentsBuilder ucb, ...) {
LOGGER.debug(ucb.toUriString());
// console log path to controller: http://localhost:80/app/test
return testData;
}
...
}
英文:
You can inject UriComponentsBuilder as parameter then use the method toUriString(). From the documentation, it is used to build a relative URI from the current request’s, this should work as your are expected Doc.
@Controller
public class RestController {
...
@GetMapping(value = "/test")
public @ResponseBody Test getTestData(UriComponentsBuilder ucb, ...) {
LOGGER.debug(ucb.toUriString());
// console log path to controller: http://localhost:80/app/test
return testData;
}
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论