How to get the URL of current page in JSF?

jsf, jsf-2, url

Solution

It's available by `HttpServletRequest#getRequestURL()` (with domain) or `getRequestURI()` (without domain). The `HttpServletRequest` itself is in turn available through JSF API via `ExternalContext#getRequest()`.

Thus, so:

public void someMethod() {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String url = request.getRequestURL().toString();
    String uri = request.getRequestURI();
    // ...
}

Or, if you're using CDI `@Named` to manage beans, and you're on JSF 2.3 or newer, then this is also possible through `javax.faces.annotation.ManagedProperty`:

@Inject @ManagedProperty("#{request.requestURL}")
private StringBuffer url; // +setter

@Inject @ManagedProperty("#{request.requestURI}")
private String uri; // +setter

public void someMethod() {
    // ...
}

Or, if you're using CDI `@Named` to manage beans, then this is also possible, also on older JSF versions:

@Inject
private HttpServletRequest request;

public void someMethod() {
    String url = request.getRequestURL().toString();
    String uri = request.getRequestURI();
    // ...
}

Or, if you're still using the since JSF 2.3 deprecated `@ManagedBean`, then this is also possible through `javax.faces.bean.ManagedProperty` (note that the bean can only be `@RequestScoped`!):

@ManagedProperty("#{request.requestURL}")
private StringBuffer url; // +setter

@ManagedProperty("#{request.requestURI}")
private String uri; // +setter

public void someMethod() {
    // ...
}

See also

- Get current page programmatically

Problem

Is there any way to get the URL of the page which is loaded? I would like the URL of the page which is loaded, in my controller i will call a method getUrlOfPage() in init() method . I need the URL source to use it as a input for exporting the context in it. How to get the URL of the page?

Original source

Related problems