Vin*_*lds 74
我假设您正在使用JSF 2和Java EE 6来获得此答案.
实际机制的实现将根据您需要原始URL的程度而有所不同.
您首先需要访问底层的servlet容器(假设为一个,而不是一个portlet容器)生成HttpServletRequest对象.使用该FacesContext对象以下列方式访问HttpServletRequest对象:
HttpServletRequest origRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
Run Code Online (Sandbox Code Playgroud)
的HttpServletRequest类提供了几种实用方法,以获得原始请求的近表示:
getRequestURL(),它提供原始请求sans查询字符串getScheme,getServerName,getServerPort,getContextPath,getServletPath,getPathInfo和getQueryString其所有输出可以顺序组合,以获得原始的请求.如果您想要URL的较小片段,则可能必须省略后面的调用.Bal*_*usC 25
您可以按如下方式获得:
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String url = req.getRequestURL().toString();
return url.substring(0, url.length() - req.getRequestURI().length()) + req.getContextPath() + "/";
// ...
Run Code Online (Sandbox Code Playgroud)
请注意,可能有更好的方法来实现这一要求.在JSF托管bean中获取原始Servlet API是一种代码异味警报.
ExternalContext您可以通过使用类似以下形式的来避免特定于容器的依赖关系:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,请注意,此代码可能并不完全与容器无关 - 其中一些方法UnsupportedOperationException在其默认实现中抛出 an 。此代码依赖于 JSF 2.0 方法。
您还应该注意,在一般情况下,使用这样的 URI 作为基础并不是引用应用程序中的资源的正确方法;ViewHandler例如, 和应该ExternalContext配合使用来创建资源 URL,以引用应用程序资源来获取资源或操作 URL 以调用 JSF 生命周期。
不幸的是,我认为没有一种通用的、与容器无关的方法来完成您在 JSF 应用程序中可能想做的所有事情,因此有时您依赖于实现,并且别无选择,只能向下转换为其他 API 。