stivlo
stivlo

Reputation: 85546

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.

Upvotes: 22

Views: 45357

Answers (2)

bimsapi
bimsapi

Reputation: 5065

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

Upvotes: 12

Boris Treukhov
Boris Treukhov

Reputation: 17774

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.

Upvotes: 36

Related Questions