以编程方式获取当前页面

Ing*_*her 62 java jsf jsf-2

在JSF支持Bean(Managed Bean的,虚焊豆,无所谓),我可以得到上下文路径的客户端是通过调用

FacesContext ctx = FacesContext.getCurrentInstance();
String path = ctx.getExternalContext().getRequestContextPath();
Run Code Online (Sandbox Code Playgroud)

这给了我客户端当前访问的路径,比如/myapplication.是否也可以得到当前页面,就像/home.faces,怎么样?

Bal*_*usC 113

You normally want to use UIViewRoot#getViewId() for this.

String viewId = facesContext.getViewRoot().getViewId();
Run Code Online (Sandbox Code Playgroud)

This is in EL also available as follows:

#{view.viewId}
Run Code Online (Sandbox Code Playgroud)

Exactly this value is reuseable in navigation case outcomes such as <h:link outcome> and <h:button outcome>.


或者,您也可以使用HttpServletRequest#getRequestURI()获取最终用户在浏览器地址栏中实际看到的内容.

String uri = ((HttpServletRequest) externalContext.getRequest()).getRequestURI();
Run Code Online (Sandbox Code Playgroud)

EL中的哪个也可用如下:

#{request.requestURI}
Run Code Online (Sandbox Code Playgroud)

确切地说,这个值可以在<h:outputLink value>或简单地重复使用<a href>.请注意,您不能将其用作导航案例结果.

  • 虽然确实如此,但他也没有明确说明他没有.我的观点是,扩展JSF的库可能会破坏您的解决方案(而PrettyFaces是一种非常常见的增强功能,因为标准实现的导航处理非常笨拙).我只是想让人们发现,你的清洁解决方案不适合他们为什么. (4认同)

Ing*_*her 13

好的,明白了,就是这样

FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest servletRequest = (HttpServletRequest) ctx.getExternalContext().getRequest();
// returns something like "/myapplication/home.faces"
String fullURI = servletRequest.getRequestURI();
Run Code Online (Sandbox Code Playgroud)