marți, 17 martie 2015

[OmniFaces utilities (2.1)] Get the concrete domain-relative URL


[OmniFaces utilities] The getBookmarkableURL() Returns the concrete domain-relative URL to the current/given view with the given params URL-encoded in the query string and optionally include view parameters as well. This URL can ultimately be used as redirect URL, or in <form action>, or in <a href>. Starting with OmniFaces 2.1, any parameter with an empty name or value will be skipped. To skip empty view parameters as well, use <o:viewParam> instead.

This utility method exist in OmniFaces 2.0, but it was fixed to work as expected in OmniFaces 2.1.

Method - get the concrete domain-relative URL to the current view:
See also: Faces#getContext()

Method - get the concrete domain-relative URL to the given view:
Usage:

Below you can see an example of using Faces#getBookmarkableURL() to obtain an URL with the following characteristics:

·         the returned URL is a concrete domain-relative URL to the current view, index.xhtml
·         it will contain two request parameters,  usernr, usertype
·         it will contain the view parameters (suppose we have two view parameters:name (whose value is evaluated to Rafael text and surname (whose value is evaluated to Nadal text))

import org.omnifaces.util.Faces;
...
Map<String, List<String>> params = new HashMap<>();
params.put("usernr", Arrays.asList("one"));
params.put("usertype", Arrays.asList("master"));
String url = Faces.getBookmarkableURL(params, true);

The url will be something like (the important part is the query string):

/app_context-root/.../index.xhtml?usernr=one&usertype=master&name=Rafael&surname=Nadal

If you need to explicitly indicate the view ID, then uses the other Faces#getBookmarkableURL(). In the next example, the generated URL will have the following characteristics:

·         the returned URL is a concrete domain-relative URL to the view, home.xhtml
·         it will contain two request parameters,  usernr, usertype
·         it will not contain the view parameters

import org.omnifaces.util.Faces;
...
Map<String, List<String>> params = new HashMap<>();
params.put("usernr", Arrays.asList("one"));
params.put("usertype", Arrays.asList("master"));
String url = Faces.getBookmarkableURL("/home", params, false);

The url will be something like (the important part is the query string): 

/app_context-root/.../home.xhtml?usernr=one&usertype=master

For example, we can use Faces#getBookmarkableURL() methods to programmatically obtain an URL that follows to be returned by a custom ViewHandler via getActionURL() method. Of course, you can find many other useful use cases to these methods. OmniFaces documentation specifies: redirect URL, <form action>, or in <a href>.

Niciun comentariu:

Trimiteți un comentariu