Friday, December 12, 2014

Spring Web: Get current request and generate base URL

Just a simple way to generate application's base URL according to the environment context using current request:


protected static String getBaseEnvLinkURL() {

   String baseEnvLinkURL=null;
   HttpServletRequest currentRequest =
      ((ServletRequestAttributes)RequestContextHolder.
       currentRequestAttributes()).getRequest();
   // lazy about determining protocol but can be done too
   baseEnvLinkURL = "http://" + currentRequest.getLocalName();
   if(currentRequest.getLocalPort() != 80) {
      baseEnvLinkURL += ":" + currentRequest.getLocalPort();
   }
   if(!StringUtils.isEmpty(currentRequest.getContextPath())) {
      baseEnvLinkURL += currentRequest.getContextPath();
   }            
   return baseEnvLinkURL;
}