简体   繁体   中英

How to find the base URL of the current webapp in Spring?

I'd like to find the absolute URL of the webapp in Spring, from the Controller. I'm aware of JSTL c:url, but I need this info from inside the Controller.

@Controller
public class AuthorizeController {

    @Autowired
    private Authorizer auth;

    @RequestMapping("/auth")
    public String sendToAuthorization() {        
        String baseUrl = "http://localhost:8080/tasks/";
        return "redirect:" +  auth.getAuthorizationUrl(baseUrl);
    }

}

As you can see the baseUrl is hardcoded, and I could provide it to the Authorizer class via Spring configuration, but I am sure that it's possible to get this information from Spring within the Controller. I tried to google "spring mvc url" and could not find a way to solve this problem.

I think that getting absolute url is only possible while processing the request as your server may have many IP addresses and domain names.

 @RequestMapping("/auth")
    public String sendToAuthorization(HttpServletRequest request) {        
    String baseUrl = String.format("%s://%s:%d/tasks/",request.getScheme(),  request.getServerName(), request.getServerPort());


        return "redirect:" +  auth.getAuthorizationUrl(baseUrl);
    }

As for the servlet, it may also have several mappings in web.xml.

similar question

PS Anyway, url parsing in runtime does not look like a good idea to me.

Very late to this answer, but a variant to Boris's answer, if you don't want to push servlet objects into method signatures, is to use RequestContextHolder from a utility class/method. This would also give the ability to abstract fallback logic (eg, pulling from a property file). Cheesy example:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(null != requestAttributes && requestAttributes instanceof ServletRequestAttributes) {
  HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
  // build URL from request
}
else {
  // fallback logic if request won't work...
}

This presumes you have org.springframework.web.context.request.RequestContextListener registered as a listener in web.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM