How to get local server host and port in Spring Boot?

后端 未结 9 1195
野性不改
野性不改 2020-12-09 02:27

I\'m starting up a Spring Boot application with mvn spring-boot:run.

One of my @Controllers needs information about the host and port the a

9条回答
  •  独厮守ぢ
    2020-12-09 02:59

    An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()

    Have a look at this code:

    @PostMapping(value = "/registration" , produces = "application/json")
    public StringResponse register(@RequestBody RequestUserDTO userDTO, 
        HttpServletRequest request) {
    request.getRequestURL().toString();
    //value: http://localhost:8080/registration
    ------
    return "";
    }
    

提交回复
热议问题