Java 以编程方式获取当前页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3253923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:47:45  来源:igfitidea点击:

Get current page programmatically

javajsfjsf-2

提问by Ingo Fischer

In a JSF backing bean (Managed Bean, Weld Bean, doesn't matter), I can get the context path the client is on by calling

在 JSF 支持 bean(托管 Bean、焊接 Bean 无关紧要)中,我可以通过调用获取客户端所在的上下文路径

FacesContext ctx = FacesContext.getCurrentInstance();
String path = ctx.getExternalContext().getRequestContextPath();

This gives me the path the client currently accesses, like /myapplication. Is it also possible to get the current page, like /home.faces, and how?

这为我提供了客户端当前访问的路径,例如/myapplication. 是否也可以获取当前页面,例如/home.faces,以及如何获取?

采纳答案by BalusC

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

您通常希望UIViewRoot#getViewId()用于此目的。

String viewId = facesContext.getViewRoot().getViewId();

This is in EL also available as follows:

这在 EL 中也可用,如下所示:

#{view.viewId}

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

正是这个值可以在导航案例结果中重用,例如<h:link outcome><h:button outcome>



Alternatively, you can also use HttpServletRequest#getRequestURI()to get whatever the enduser is actually seeing in the browser address bar.

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

String uri = ((HttpServletRequest) externalContext.getRequest()).getRequestURI();

Which is in EL also available as follows:

这在 EL 中也可用,如下所示:

#{request.requestURI}

Exactly this value is reuseable in <h:outputLink value>or plain <a href>. Note that you can't use it as navigation case outcome.

正是这个值可以在<h:outputLink value>或 plain 中重用<a href>。请注意,您不能将其用作导航案例结果。

回答by Ingo Fischer

Ok, got it, it's

好的,明白了,就是

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

回答by Catfish

String uri = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRequestURI();

回答by jsina

 String str = ((HttpServletRequest) FacesContext.getCurrentInstance() 
 .getExternalContext().getRequest()).getRequestURI(); 
 System.out.println(str);