0

I want my @RestController to return an absolute url path to my webserver. But the path should not be hardcoded, instead derived from the application server where the spring application runs in.

@RestController
public class FileService {
     @GetMapping("/list")
     public String getFiles(String key) {
            String filepath = manager.getFile(key);
            //TODO how to return the file with absolute path to webserver?
     }
}

Also, if the user requests the file via http, the server should respond with http. Likewise, if https is requested, https should be prefixed before the absolute url.

Question: how can I get the absolute path inside the controller dynamically?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

3

You can extract it from HttpServletRequest:

 @GetMapping("/list")
 public String getFiles(@RequestParam("key") String key, HttpServletRequest req) {
        String filepath = manager.getFile(key);
        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
 }
Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
  • There is no static utility class to optain the base webserver path? Because I'm not interested in the query path, just the domain/main path. – membersound Oct 30 '18 at 13:34
  • @membersound Do you mean, file path to your server or URL? – Branislav Lazic Oct 30 '18 at 13:49
  • From `https://www.myserver.com/myapp/some/rest/path?query=params` I want to get `https://www.myserver.com/myapp`. This is my application root that I want to fetch dynamically. – membersound Oct 30 '18 at 14:02
  • 1
    @membersound Updated. – Branislav Lazic Oct 30 '18 at 14:31
  • And there is no way of getting that path only once on startup of the web application? Because the path built will always be the same on any request. So I'd prefer not having to build it from inside the actual request, but sometime before, eg during `@PostConstruct`. Can I access the server name, port, context path somehow without the `HttpServletRequest`? – membersound Oct 30 '18 at 15:57
  • 1
    @membersound Yes there is. Actually, two ways come to my mind. First one: Cache the path by simply putting it to default `CacheManager`. However, if you want to have your app. stateless, then it might be bad. Second: Just put it in properties file and load it via `@Value` annotation. Because, I can't see what could be an obstacle not to determine that URL before starting a server. – Branislav Lazic Oct 30 '18 at 16:02
0

Use methods from HttpServletRequest which you can obtain by passing it to controller method:

@GetMapping("/list")
public String getFiles(@RequestParam("key") String key, HttpServletRequest request) {
     String serverAddress = String.format(
          "%s://%s:%d",
          request.geScheme(),
          request.getServerName(),
          request.getServerPort());
}