Alex Rivera | Logout

How do I get request url in jsf managed bean without the requested servlet?

Asked 2011-06-01T05:01:59.207
48

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.

Edit
Report

1 Answer

7

You can avoid container-specific dependencies by using the ExternalContext in something like this form:

public String getApplicationUri() {
  try {
    FacesContext ctxt = FacesContext.getCurrentInstance();
    ExternalContext ext = ctxt.getExternalContext();
    URI uri = new URI(ext.getRequestScheme(),
          null, ext.getRequestServerName(), ext.getRequestServerPort(),
          ext.getRequestContextPath(), null, null);
    return uri.toASCIIString();
  } catch (URISyntaxException e) {
    throw new FacesException(e);
  }
}

However, note that this code may not be entirely container-agnostic - some of those methods throw an UnsupportedOperationException in their default implementation. This code relies on JSF 2.0 methods.

You should also note that using a URI like this as a base is not the correct way to refer to a resource in your application in the general case; the ViewHandler and ExternalContext should be used in concert to create resource URLs for referring to application resources to fetch resources or action URLs for invoking the JSF lifecycle, for example.

Unfortunately, I don't think there is a general, container-agnostic way to do everything you might want to do in a JSF app, so sometimes you're dependent on the implementation and you have little choice but to cast down to other APIs.

answered 2011-06-01T13:59:24.487

Your Answer