Search code examples
springspring-mvcspring-restspring-web

How to get absolute webserver path in a Spring @RestController?


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?


Solution

  • 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();
     }