Get current page programmatically

JavaJsfJsf 2

Java Problem Overview


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

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?

Java Solutions


Solution 1 - Java

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

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

This is in EL also available as follows:

#{view.viewId}

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


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

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

Which is in EL also available as follows:

#{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.

Solution 2 - Java

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();

Solution 3 - Java

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

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWolkenarchitektView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaWolkenarchitektView Answer on Stackoverflow
Solution 3 - JavaCatfishView Answer on Stackoverflow
Solution 4 - JavajsinaView Answer on Stackoverflow