Assuming the URL is http://localhost:8080/project-name/resource.xhtml,
I want to obtain the following http://localhost:8080/project-name in a JSF managed bean.
You can get it as follows:
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String url = req.getRequestURL().toString();
return url.substring(0, url.length() - req.getRequestURI().length()) + req.getContextPath() + "/";
// ...
Note that there are possibly better ways to achieve the requirement. Getting the raw Servlet API inside a JSF managed bean is a code smell alarm.