Sure, here’s the translation: 从内部将 URL 记录到 Spring 控制器

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月14日 20:44:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63413024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定