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

前端 未结 4 1581
予麋鹿
予麋鹿 2020-12-07 22:35

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.

4条回答
  •  庸人自扰
    2020-12-07 23:19

    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.

提交回复
热议问题