22

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.

stivlo
  • 83,644
  • 31
  • 142
  • 199

2 Answers2

36

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

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

Community
  • 1
  • 1
Boris Treukhov
  • 17,493
  • 9
  • 70
  • 91
  • 1
    I understand and it could have mod_jk, url rewrite and the servlet would not be aware of that. Also reading the other question that you've linked, I think that my best option is thus injecting this base URL in the bean with spring XML configuration. Thanks. – stivlo Jul 25 '11 at 15:39
12

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 (e.g., 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

bimsapi
  • 4,985
  • 2
  • 19
  • 27