public final class Faces extends Object
Collection of utility methods for the JSF API that are mainly shortcuts for obtaining stuff from the thread local
FacesContext
. In effects, it 'flattens' the hierarchy of nested objects. Do note that using the hierarchy is
actually a better software design practice, but can lead to verbose code.
Next to those oneliner delegate calls, there are also some helpful methods which eliminates multiline boilerplate
code, such as getLocale()
which returns sane fallback values, a more convenient
redirect(String, String...)
which automatically prepends the context path when the path does not start with
/
and offers support for URL encoding of request parameters supplied by varargs argument, and several
useful sendFile(File, boolean)
methods which allows you to provide a File
, byte[]
or
InputStream
as a download to the client.
Some examples:
// Get a session attribute (no explicit cast necessary!). User user = Faces.getSessionAttribute("user");
// Evaluate EL programmatically (no explicit cast necessary!). Item item = Faces.evaluateExpressionGet("#{item}");
// Get a cookie value. String cookieValue = Faces.getRequestCookie("cookieName");
// Get all supported locales with default locale as first item. List<Locale> supportedLocales = Faces.getSupportedLocales();
// Check in e.g. preRenderView if session has been timed out. if (Faces.hasSessionTimedOut()) { Messages.addGlobalWarn("Oops, you have been logged out because your session was been timed out!"); }
// Get value of <f:metadata><f:attribute name="foo"> of different view without building it. String foo = Faces.getMetadataAttribute("/other.xhtml", "foo");
// Send a redirect with parameters UTF-8 encoded in query string. Faces.redirect("product.xhtml?id=%d&name=%s", product.getId(), product.getName());
// Invalidate the session and send a redirect. public void logout() throws IOException { Faces.invalidateSession(); Faces.redirect("login.xhtml"); // Can by the way also be done by return "login?faces-redirect=true" if in action method. }
// Provide a file as attachment. public void download() throws IOException { Faces.sendFile(new File("/path/to/file.ext"), true); }
Note that there's normally a minor overhead in obtaining the thread local FacesContext
. In case client code
needs to call methods in this class multiple times it's expected that performance will be slightly better if instead
the FacesContext
is obtained once and the required methods are called on that, although the difference is
practically negligible when used in modern server hardware.
In such case, consider using FacesLocal
instead. The difference with Faces
is that no one method of
FacesLocal
obtains the FacesContext
from the current thread by
FacesContext.getCurrentInstance()
. This job is up to the caller.
FacesLocal
,
Servlets
Modifier and Type | Method and Description |
---|---|
static void |
addResponseCookie(String name,
String value,
int maxAge)
Add a cookie with given name, value and maxage to the HTTP response.
|
static void |
addResponseCookie(String name,
String value,
String path,
int maxAge)
Add a cookie with given name, value, path and maxage to the HTTP response.
|
static void |
addResponseCookie(String name,
String value,
String domain,
String path,
int maxAge)
Add a cookie with given name, value, domain, path and maxage to the HTTP response.
|
static void |
addResponseHeader(String name,
String value)
Add a header with given name and value to the HTTP response.
|
static boolean |
authenticate()
Trigger the default container managed authentication mechanism on the current request.
|
static <T> T |
evaluateExpressionGet(String expression)
Programmatically evaluate the given EL expression and return the evaluated value.
|
static void |
evaluateExpressionSet(String expression,
Object value)
Programmatically evaluate the given EL expression and set the given value.
|
static Application |
getApplication()
Returns the application singleton.
|
static <T> T |
getApplicationAttribute(String name)
Returns the application scope attribute value associated with the given name.
|
static Application |
getApplicationFromFactory()
Gets the JSF Application singleton from the FactoryFinder.
|
static Map<String,Object> |
getApplicationMap()
Returns the application scope map.
|
static String |
getBookmarkableURL(Collection<? extends ParamHolder> params,
boolean includeViewParams)
Returns the concrete domain-relative URL to the current view with the given params URL-encoded in the query
string and optionally include view parameters as well.
|
static String |
getBookmarkableURL(Map<String,List<String>> params,
boolean includeViewParams)
Returns the concrete domain-relative URL to the current view with the given params URL-encoded in the query
string and optionally include view parameters as well.
|
static String |
getBookmarkableURL(String viewId,
Collection<? extends ParamHolder> params,
boolean includeViewParams)
Returns the concrete domain-relative URL to the given view with the given params URL-encoded in the query
string and optionally include view parameters as well.
|
static String |
getBookmarkableURL(String viewId,
Map<String,List<String>> params,
boolean includeViewParams)
Returns the concrete domain-relative URL to the given view with the given params URL-encoded in the query
string and optionally include view parameters as well.
|
static String |
getBundleString(String key)
Gets a string for the given key searching declared resource bundles, order by declaration in
faces-config.xml . |
static FacesContext |
getContext()
Returns the current faces context.
|
static FacesContext |
getContext(ELContext elContext)
Returns the faces context that's stored in an ELContext.
|
static <T> T |
getContextAttribute(String name)
Returns the Faces context attribute value associated with the given name.
|
static PhaseId |
getCurrentPhaseId()
Returns the current phase ID.
|
static Locale |
getDefaultLocale()
Returns the default locale, or
null if there is none. |
static ELContext |
getELContext()
Returns the current EL context.
|
static ExternalContext |
getExternalContext()
Returns the current external context.
|
static <T> T |
getFaceletAttribute(String name)
Returns the Facelet attribute value associated with the given name.
|
static FaceletContext |
getFaceletContext()
Returns the Facelet context.
|
static Flash |
getFlash()
Returns the flash scope.
|
static <T> T |
getFlashAttribute(String name)
Returns the flash scope attribute value associated with the given name.
|
static String |
getForwardRequestQueryString()
Returns the original HTTP request query string behind this forwarded request, if any.
|
static String |
getForwardRequestURI()
Returns the original HTTP request URI behind this forwarded request, if any.
|
static String |
getForwardRequestURIWithQueryString()
Returns the original HTTP request URI with query string behind this forwarded request, if any.
|
static String |
getImplInfo()
Returns the implementation information of currently loaded JSF implementation.
|
static String |
getInitParameter(String name)
Returns the application initialization parameter.
|
static Map<String,String> |
getInitParameterMap()
Returns the application initialization parameter map.
|
static Locale |
getLocale()
Returns the current locale.
|
static String |
getMapping()
Determines and returns the faces servlet mapping used in the current request.
|
static ResourceBundle |
getMessageBundle()
Returns the application message bundle as identified by
<message-bundle> in
faces-config.xml . |
static <T> T |
getMetadataAttribute(String name)
Returns the metadata attribute of the current view associated with the given name.
|
static <T> T |
getMetadataAttribute(String viewId,
String name)
Returns the metadata attribute of the given view ID associated with the given name.
|
static Map<String,Object> |
getMetadataAttributes()
Returns the metadata attribute map of the current view, or an empty map if there is no view metadata.
|
static Map<String,Object> |
getMetadataAttributes(String viewId)
Returns the metadata attribute map of the given view ID, or an empty map if there is no view metadata.
|
static String |
getMimeType(String name)
Returns the mime type for the given file name.
|
static String |
getRealPath(String webContentPath)
Returns the absolute disk file system path representation of the given web content path.
|
static String |
getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
|
static String |
getRemoteUser()
Returns the name of the logged-in user for container managed FORM based authentication, if any.
|
static HttpServletRequest |
getRequest()
Returns the HTTP servlet request.
|
static <T> T |
getRequestAttribute(String name)
Returns the request scope attribute value associated with the given name.
|
static String |
getRequestBaseURL()
Returns the HTTP request base URL.
|
static String |
getRequestContextPath()
Returns the HTTP request context path.
|
static String |
getRequestCookie(String name)
Returns the value of the HTTP request cookie associated with the given name.
|
static String |
getRequestDomainURL()
Returns the HTTP request domain URL.
|
static String |
getRequestHeader(String name)
Returns the HTTP request header value associated with the given name.
|
static Map<String,String> |
getRequestHeaderMap()
Returns the HTTP request header map.
|
static String[] |
getRequestHeaderValues(String name)
Returns the HTTP request header values associated with the given name.
|
static Map<String,String[]> |
getRequestHeaderValuesMap()
Returns the HTTP request header values map.
|
static String |
getRequestHostname()
Returns the HTTP request hostname.
|
static Map<String,Object> |
getRequestMap()
Returns the request scope map.
|
static String |
getRequestParameter(String name)
Returns the HTTP request parameter value associated with the given name.
|
static Map<String,String> |
getRequestParameterMap()
Returns the HTTP request parameter map.
|
static String[] |
getRequestParameterValues(String name)
Returns the HTTP request parameter values associated with the given name.
|
static Map<String,String[]> |
getRequestParameterValuesMap()
Returns the HTTP request parameter values map.
|
static String |
getRequestPathInfo()
Returns the HTTP request path info.
|
static String |
getRequestQueryString()
Returns the HTTP request query string.
|
static Map<String,List<String>> |
getRequestQueryStringMap()
Returns the HTTP request query string as parameter values map.
|
static String |
getRequestServletPath()
Returns the HTTP request servlet path.
|
static String |
getRequestURI()
Returns the HTTP request URI.
|
static String |
getRequestURIWithQueryString()
Returns the HTTP request URI with query string.
|
static String |
getRequestURL()
Returns the HTTP request URL.
|
static String |
getRequestURLWithQueryString()
Returns the HTTP request URL with query string.
|
static URL |
getResource(String path)
Returns a URL for an application resource mapped to the specified path, if it exists; otherwise, return
null . |
static InputStream |
getResourceAsStream(String path)
Returns an input stream for an application resource mapped to the specified path, if it exists; otherwise,
return
null . |
static ResourceBundle |
getResourceBundle(String var)
Returns the application resource bundle as identified by the given
<var> of the
<resource-bundle> in faces-config.xml . |
static Map<String,ResourceBundle> |
getResourceBundles()
Returns all application resource bundles registered as
<resource-bundle> in
faces-config.xml . |
static Set<String> |
getResourcePaths(String path)
Returns a set of available application resource paths matching the specified path.
|
static HttpServletResponse |
getResponse()
Returns the HTTP servlet response.
|
static int |
getResponseBufferSize()
Returns the HTTP response buffer size.
|
static String |
getResponseCharacterEncoding()
Returns the HTTP response character encoding.
|
static String |
getServerInfo()
Returns the server information of currently running application server implementation.
|
static ServletContext |
getServletContext()
Returns the servlet context.
|
static HttpSession |
getSession()
Returns the HTTP session and creates one if one doesn't exist.
|
static HttpSession |
getSession(boolean create)
Returns the HTTP session and creates one if one doesn't exist and
create argument is
true , otherwise don't create one and return null . |
static <T> T |
getSessionAttribute(String name)
Returns the session scope attribute value associated with the given name.
|
static long |
getSessionCreationTime()
Returns the time when the HTTP session was created, measured in epoch time.
|
static String |
getSessionId()
Returns a string containing the unique identifier assigned to this session.
|
static long |
getSessionLastAccessedTime()
Returns the time of the previous request associated with the current HTTP session, measured in epoch time.
|
static Map<String,Object> |
getSessionMap()
Returns the session scope map.
|
static int |
getSessionMaxInactiveInterval()
Returns the HTTP session timeout in seconds.
|
static List<Locale> |
getSupportedLocales()
Returns a list of all supported locales on this application, with the default locale as the first item, if any.
|
static <T> T |
getViewAttribute(String name)
Returns the view scope attribute value associated with the given name.
|
static ViewDeclarationLanguage |
getViewDeclarationLanguage()
Returns the
ViewDeclarationLanguage associated with the "current" view ID. |
static String |
getViewId()
Returns the ID of the current view root, or
null if there is no view. |
static Map<String,Object> |
getViewMap()
Returns the view scope map.
|
static Map<String,List<String>> |
getViewParameterMap()
Returns the view parameters of the current view as a parameter map, or an empty map if there is no view.
|
static Collection<UIViewParameter> |
getViewParameters()
Returns the view parameters of the current view, or an empty collection if there is no view.
|
static UIViewRoot |
getViewRoot()
Returns the current view root.
|
static boolean |
hasContext()
Returns
true when the current faces context is available (i.e. |
static boolean |
hasSession()
Returns whether the HTTP session has already been created.
|
static boolean |
hasSessionTimedOut()
Returns whether the HTTP session has been timed out for the current request.
|
static void |
invalidateSession()
Invalidates the current HTTP session.
|
static boolean |
isAjaxRequest()
Returns whether the current request is an ajax request.
|
static boolean |
isDevelopment()
Returns whether we're in development stage.
|
static boolean |
isPostback()
Returns whether the current request is a postback.
|
static boolean |
isPrefixMapping()
Returns whether the faces servlet mapping used in the current request is a prefix mapping.
|
static boolean |
isPrefixMapping(String mapping)
Returns whether the given faces servlet mapping is a prefix mapping.
|
static boolean |
isRenderResponse()
Returns
true if we're currently in the render response phase. |
static boolean |
isResponseCommitted()
Returns whether the response is already committed.
|
static boolean |
isResponseComplete()
Returns
true if the FacesContext.responseComplete() has been called. |
static boolean |
isSessionNew()
Returns whether the HTTP session has been created for the first time in the current request.
|
static boolean |
isUserInRole(String role)
Returns whether the currently logged-in user has the given role.
|
static boolean |
isValidationFailed()
Returns whether the validations phase of the current request has failed.
|
static void |
login(String username,
String password)
Perform programmatic login for container managed FORM based authentication.
|
static void |
logout()
Perform programmatic logout for container managed FORM based authentication.
|
static void |
navigate(String outcome)
Perform the JSF navigation to the given outcome.
|
static String |
normalizeViewId(String path)
Normalize the given path as a valid view ID based on the current mapping, if necessary.
|
static void |
redirect(String url,
String... paramValues)
Sends a temporary (302) redirect to the given URL.
|
static void |
redirectPermanent(String url,
String... paramValues)
Sends a permanent (301) redirect to the given URL.
|
static <T> T |
removeApplicationAttribute(String name)
Removes the application scope attribute value associated with the given name.
|
static <T> T |
removeFlashAttribute(String name)
Removes the flash scope attribute value associated with the given name.
|
static <T> T |
removeRequestAttribute(String name)
Removes the request scope attribute value associated with the given name.
|
static void |
removeResponseCookie(String name,
String path)
Remove the cookie with given name and path from the HTTP response.
|
static <T> T |
removeSessionAttribute(String name)
Removes the session scope attribute value associated with the given name.
|
static <T> T |
removeViewAttribute(String name)
Removes the view scope attribute value associated with the given name.
|
static void |
renderResponse()
Signals JSF that, as soon as the current phase of the lifecycle has been completed, control should be passed to
the Render Response phase, bypassing any phases that have not been executed yet.
|
static <T> T |
resolveExpressionGet(Object base,
String property)
Programmatically EL-resolve the given property on the given base object and return the resolved value.
|
static void |
resolveExpressionSet(Object base,
String property,
Object value)
Programmatically EL-resolve the given property on the given base object and set the given value.
|
static void |
responseComplete()
Signals JSF that the response for this request has already been generated (such as providing a file download),
and that the lifecycle should be terminated as soon as the current phase is completed.
|
static void |
responseReset()
Resets the current response.
|
static void |
responseSendError(int status,
String message)
Sends a HTTP response error with the given status and message.
|
static void |
sendFile(byte[] content,
String filename,
boolean attachment)
Send the given byte array as a file to the response.
|
static void |
sendFile(File file,
boolean attachment)
Send the given file to the response.
|
static void |
sendFile(InputStream content,
String filename,
boolean attachment)
Send the given input stream as a file to the response.
|
static void |
setApplicationAttribute(String name,
Object value)
Sets the application scope attribute value associated with the given name.
|
static void |
setContext(FacesContext context)
Sets the given faces context as current instance.
|
static void |
setContextAttribute(String name,
Object value)
Sets the Faces context attribute value associated with the given name.
|
static void |
setFaceletAttribute(String name,
Object value)
Sets the Facelet attribute value associated with the given name.
|
static void |
setFlashAttribute(String name,
Object value)
Sets the flash scope attribute value associated with the given name.
|
static void |
setLocale(Locale locale)
Set the locale of the current view, which is to be used in localizing of the response.
|
static void |
setRequestAttribute(String name,
Object value)
Sets the request scope attribute value associated with the given name.
|
static void |
setResponseStatus(int status)
Sets the HTTP response status code.
|
static void |
setSessionAttribute(String name,
Object value)
Sets the session scope attribute value associated with the given name.
|
static void |
setSessionMaxInactiveInterval(int seconds)
Sets the HTTP session timeout in seconds.
|
static void |
setViewAttribute(String name,
Object value)
Sets the view scope attribute value associated with the given name.
|
static void |
setViewRoot(String viewId)
Sets the current view root to the given view ID.
|
static void |
validationFailed()
Signals JSF that the validations phase of the current request has failed.
|
public static FacesContext getContext()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
FacesContext.getCurrentInstance()
public static FacesContext getContext(ELContext elContext)
Note that this only works for an ELContext that is created in the context of JSF.
elContext
- the EL context to obtain the faces context from.public static void setContext(FacesContext context)
FacesContextWrapper
which you'd like to (temporarily) use as the current instance of the faces context.context
- The faces context to be set as the current instance.public static boolean hasContext()
true
when the current faces context is available (i.e. it is not null
).true
when the current faces context is available.public static ExternalContext getExternalContext()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
FacesContext.getExternalContext()
public static Application getApplication()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
FacesContext.getApplication()
public static Application getApplicationFromFactory()
This method is an alternative for getApplication()
for those situations where the
FacesContext
isn't available.
public static String getImplInfo()
Package.getImplementationTitle()
,
Package.getImplementationVersion()
public static String getServerInfo()
ServletContext.getServerInfo()
public static boolean isDevelopment()
javax.faces.PROJECT_STAGE
context parameter in web.xml
is set to Development
.true
if we're in development stage, otherwise false
.Application.getProjectStage()
public static String getMapping()
/faces/*
), then this returns the whole path, with a leading slash (e.g. /faces
). If JSF
is suffix mapped (e.g. *.xhtml
), then this returns the whole extension (e.g. .xhtml
).getRequestPathInfo()
,
getRequestServletPath()
public static boolean isPrefixMapping()
true
if the faces servlet mapping used in the current request is a prefix mapping, otherwise
false
.getMapping()
,
isPrefixMapping(String)
public static boolean isPrefixMapping(String mapping)
isPrefixMapping()
when you already have obtained the mapping from getMapping()
so that the
mapping won't be calculated twice.mapping
- The mapping to be tested.true
if the faces servlet mapping used in the current request is a prefix mapping, otherwise
false
.NullPointerException
- When mapping is null
.public static PhaseId getCurrentPhaseId()
FacesContext.getCurrentPhaseId()
public static void validationFailed()
isValidationFailed()
in Java and by
#{facesContext.validationFailed}
in EL.FacesContext.validationFailed()
public static boolean isValidationFailed()
true
if the validations phase of the current request has failed, otherwise
false
.FacesContext.isValidationFailed()
public static ELContext getELContext()
FacesContext.getELContext()
public static <T> T evaluateExpressionGet(String expression)
T
- The expected return type.expression
- The EL expression to be evaluated.ClassCastException
- When T
is of wrong type.Application.evaluateExpressionGet(FacesContext, String, Class)
public static void evaluateExpressionSet(String expression, Object value)
expression
- The EL expression to be evaluated.value
- The value to be set in the property behind the given EL expression.Application.getExpressionFactory()
,
ExpressionFactory.createValueExpression(ELContext, String, Class)
,
ValueExpression.setValue(ELContext, Object)
public static <T> T resolveExpressionGet(Object base, String property)
T
- The expected return type.base
- The base object whose property value is to be returned, or null to resolve a top-level variable.property
- The property or variable to be resolved on the given base.ClassCastException
- When T
is of wrong type.Application.getELResolver()
,
ELResolver.getValue(ELContext, Object, Object)
public static void resolveExpressionSet(Object base, String property, Object value)
base
- The base object whose property value is to be set, or null to set a top-level variable.property
- The property or variable to be set on the given base.value
- The value to be set in the property on the given base.Application.getELResolver()
,
ELResolver.setValue(ELContext, Object, Object, Object)
public static <T> T getContextAttribute(String name)
T
- The expected return type.name
- The Faces context attribute name.ClassCastException
- When T
is of wrong type.FacesContext.getAttributes()
public static void setContextAttribute(String name, Object value)
name
- The Faces context attribute name.value
- The Faces context attribute value.FacesContext.getAttributes()
public static UIViewRoot getViewRoot()
FacesContext.getViewRoot()
public static void setViewRoot(String viewId)
viewId
- The ID of the view which needs to be set as the current view root.ViewHandler.createView(FacesContext, String)
,
FacesContext.setViewRoot(UIViewRoot)
public static String getViewId()
null
if there is no view.null
if there is no view.UIViewRoot.getViewId()
public static ViewDeclarationLanguage getViewDeclarationLanguage()
ViewDeclarationLanguage
associated with the "current" view ID.
The current view ID is the view ID that's set for the view root that's associated with the current faces context.
ViewDeclarationLanguage
associated with the "current" view ID.public static String normalizeViewId(String path)
path
- The path to be normalized as a valid view ID based on the current mapping.getMapping()
,
isPrefixMapping(String)
public static Collection<UIViewParameter> getViewParameters()
ViewMetadata.getViewParameters(UIViewRoot)
public static Map<String,List<String>> getViewParameterMap()
ViewHandler.getBookmarkableURL(FacesContext, String, Map, boolean)
.ViewMetadata.getViewParameters(UIViewRoot)
public static Map<String,Object> getMetadataAttributes(String viewId)
viewId
- The view ID to return the metadata attribute map for.ViewDeclarationLanguage.getViewMetadata(FacesContext, String)
public static Map<String,Object> getMetadataAttributes()
UIComponentBase.getAttributes()
public static <T> T getMetadataAttribute(String viewId, String name)
getViewAttribute(String)
.T
- The expected return type.viewId
- The view ID to return the metadata attribute for.name
- The metadata attribute name.ClassCastException
- When T
is of wrong type.ViewDeclarationLanguage.getViewMetadata(FacesContext, String)
public static <T> T getMetadataAttribute(String name)
getViewAttribute(String)
.T
- The expected return type.name
- The metadata attribute name.ClassCastException
- When T
is of wrong type.UIComponentBase.getAttributes()
public static Locale getLocale()
UIViewRoot.getLocale()
,
ExternalContext.getRequestLocale()
,
Application.getDefaultLocale()
,
Locale.getDefault()
public static Locale getDefaultLocale()
null
if there is none.null
if there is none.Application.getDefaultLocale()
public static List<Locale> getSupportedLocales()
faces-config.xml
.Application.getDefaultLocale()
,
Application.getSupportedLocales()
public static void setLocale(Locale locale)
locale
- The locale of the current view.IllegalStateException
- When there is no view (i.e. when it is null
). This can happen if the
method is called at the wrong moment in the JSF lifecycle, e.g. before the view has been restored/created.UIViewRoot.setLocale(Locale)
public static ResourceBundle getMessageBundle()
<message-bundle>
in
faces-config.xml
. The instance is already localized via getLocale()
. If there is no
<message-bundle>
, then this method just returns null
.<message-bundle>
in faces-config.xml
.MissingResourceException
- When the <message-bundle>
in faces-config.xml
does not refer an existing resource in the classpath.Application.getMessageBundle()
public static ResourceBundle getResourceBundle(String var)
<var>
of the
<resource-bundle>
in faces-config.xml
. If there is no
<resource-bundle>
with the given <var>
, then this method just returns
null
.var
- The value of the <var>
which identifies the <resource-bundle>
in
faces-config.xml
.<var>
of the
<resource-bundle>
in faces-config.xml
.MissingResourceException
- When the <resource-bundle>
as identified by the given
<var>
in faces-config.xml
does not refer an existing resource in the classpath.Application.getResourceBundle(FacesContext, String)
public static Map<String,ResourceBundle> getResourceBundles()
<resource-bundle>
in
faces-config.xml
. If there are no resource bundles registered, then this method just returns an
empty map.<resource-bundle>
in
faces-config.xml
.
<base-name>
of the <resource-bundle>
in faces-config.xml
.MissingResourceException
- When the <resource-bundle>
in faces-config.xml
does not refer an existing resource in the classpath.Application.getResourceBundle(FacesContext, String)
public static String getBundleString(String key)
faces-config.xml
.
If the string is missing, then this method returns ???key???
.key
- The bundle key.faces-config.xml
.public static void navigate(String outcome)
outcome
- The navigation outcome.Application.getNavigationHandler()
,
NavigationHandler.handleNavigation(FacesContext, String, String)
public static String getBookmarkableURL(Map<String,List<String>> params, boolean includeViewParams)
<form action>
, or in <a href>
. Any parameter with an empty name or value
will be skipped. To skip empty view parameters as well, use <o:viewParam>
instead.params
- The parameters to be URL-encoded in the query string. Can be null
.includeViewParams
- Whether the view parameters of the current view should be included as well.IllegalStateException
- When there is no view (i.e. when it is null
). This can happen if the
method is called at the wrong moment in the JSF lifecycle, e.g. before the view has been restored/created.ViewHandler.getBookmarkableURL(FacesContext, String, Map, boolean)
public static String getBookmarkableURL(String viewId, Map<String,List<String>> params, boolean includeViewParams)
<form action>
, or in <a href>
. Any parameter with an empty name or value
will be skipped. To skip empty view parameters as well, use <o:viewParam>
instead.viewId
- The view ID to create the bookmarkable URL for.params
- The parameters to be URL-encoded in the query string. Can be null
.includeViewParams
- Whether the view parameters of the current view which are also declared in the target
view should be included as well. Note thus that this does not include the view parameters which are not declared
in the target view!ViewHandler.getBookmarkableURL(FacesContext, String, Map, boolean)
public static String getBookmarkableURL(Collection<? extends ParamHolder> params, boolean includeViewParams)
<form action>
, or in <a href>
. Any parameter with an empty name or value
will be skipped. To skip empty view parameters as well, use <o:viewParam>
instead.params
- The parameters to be URL-encoded in the query string. Can be null
.includeViewParams
- Whether the view parameters of the current view should be included as well.IllegalStateException
- When there is no view (i.e. when it is null
). This can happen if the
method is called at the wrong moment in the JSF lifecycle, e.g. before the view has been restored/created.ViewHandler.getBookmarkableURL(FacesContext, String, Map, boolean)
public static String getBookmarkableURL(String viewId, Collection<? extends ParamHolder> params, boolean includeViewParams)
<form action>
, or in <a href>
. Any parameter with an empty name or value
will be skipped. To skip empty view parameters as well, use <o:viewParam>
instead.viewId
- The view ID to create the bookmarkable URL for.params
- The parameters to be URL-encoded in the query string. Can be null
.includeViewParams
- Whether the view parameters of the current view which are also declared in the target
view should be included as well. Note thus that this does not include the view parameters which are not declared
in the target view!ViewHandler.getBookmarkableURL(FacesContext, String, Map, boolean)
public static FaceletContext getFaceletContext()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
FaceletContext
public static <T> T getFaceletAttribute(String name)
<ui:param>
which is been declared inside the Facelet file, or is been passed into the Facelet
file by e.g. an <ui:include>
.T
- The expected return type.name
- The Facelet attribute name.ClassCastException
- When T
is of wrong type.FaceletContext.getAttribute(String)
public static void setFaceletAttribute(String name, Object value)
<ui:param>
which is been declared inside the Facelet file, or is been passed into the Facelet
file by e.g. an <ui:include>
.name
- The Facelet attribute name.value
- The Facelet attribute value.FaceletContext.setAttribute(String, Object)
public static HttpServletRequest getRequest()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
ExternalContext.getRequest()
public static boolean isAjaxRequest()
true
for an ajax request, false
for a non-ajax (synchronous) request.PartialViewContext.isAjaxRequest()
public static boolean isPostback()
true
for a postback, false
for a non-postback (GET) request.FacesContext.isPostback()
public static Map<String,String> getRequestParameterMap()
ExternalContext.getRequestParameterMap()
public static String getRequestParameter(String name)
name
- The HTTP request parameter name.ExternalContext.getRequestParameterMap()
public static Map<String,String[]> getRequestParameterValuesMap()
ExternalContext.getRequestParameterValuesMap()
public static String[] getRequestParameterValues(String name)
name
- The HTTP request parameter name.ExternalContext.getRequestParameterValuesMap()
public static Map<String,String> getRequestHeaderMap()
ExternalContext.getRequestHeaderMap()
public static String getRequestHeader(String name)
name
- The HTTP request header name.ExternalContext.getRequestHeaderMap()
public static Map<String,String[]> getRequestHeaderValuesMap()
ExternalContext.getRequestHeaderValuesMap()
public static String[] getRequestHeaderValues(String name)
name
- The HTTP request header name.ExternalContext.getRequestHeaderValuesMap()
public static String getRequestContextPath()
ExternalContext.getRequestContextPath()
public static String getRequestServletPath()
/faces/*
), then this returns
the whole prefix mapping (e.g. /faces
). If JSF is suffix mapped (e.g. *.xhtml
), then
this returns the whole part after the context path, with a leading slash.ExternalContext.getRequestServletPath()
public static String getRequestPathInfo()
/faces/*
), then this returns the
whole part after the prefix mapping, with a leading slash. If JSF is suffix mapped (e.g. *.xhtml
),
then this returns null
.ExternalContext.getRequestPathInfo()
public static String getRequestHostname()
ServletRequest.getServerName()
as its
outcome can be influenced by proxies.IllegalArgumentException
- When the URL is malformed. This is however unexpected as the request would
otherwise not have hit the server at all.HttpServletRequest.getRequestURL()
public static String getRequestBaseURL()
<base>
tag.HttpServletRequest.getRequestURL()
,
HttpServletRequest.getRequestURI()
,
HttpServletRequest.getContextPath()
public static String getRequestDomainURL()
HttpServletRequest.getRequestURL()
,
HttpServletRequest.getRequestURI()
public static String getRequestURL()
HttpServletRequest.getRequestURL()
public static String getRequestURI()
HttpServletRequest.getRequestURI()
public static String getRequestQueryString()
?
in the request URL as the
enduser sees in browser address bar.HttpServletRequest.getQueryString()
public static Map<String,List<String>> getRequestQueryStringMap()
getRequestParameterValuesMap()
, which contains both
the request URL (GET) parameters and and the request body (POST) parameters. This is ready for usage in among
others ViewHandler.getBookmarkableURL(FacesContext, String, Map, boolean)
.HttpServletRequest.getQueryString()
public static String getRequestURLWithQueryString()
HttpServletRequest.getRequestURL()
,
HttpServletRequest.getQueryString()
public static String getRequestURIWithQueryString()
HttpServletRequest.getRequestURI()
,
HttpServletRequest.getQueryString()
public static String getForwardRequestURI()
public static String getForwardRequestQueryString()
public static String getForwardRequestURIWithQueryString()
public static String getRemoteAddr()
X-Forwarded-For
request header and if it's present, then return its first IP address, else just
return ServletRequest.getRemoteAddr()
unmodified.ServletRequest.getRemoteAddr()
public static HttpServletResponse getResponse()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
ExternalContext.getResponse()
public static int getResponseBufferSize()
javax.faces.FACELETS_BUFFER_SIZE
context parameter is been set, then it's the context parameter value which will be returned. Otherwise it
returns the implementation independent default value, which is 1024 in Mojarra.ExternalContext.getResponseBufferSize()
public static String getResponseCharacterEncoding()
ExternalContext.getResponseCharacterEncoding()
public static void setResponseStatus(int status)
HttpServletResponse
for
this. For example, Faces.setResponseStatus(HttpServletResponse.SC_BAD_REQUEST)
.status
- The HTTP status code to be set on the current response.public static void redirect(String url, String... paramValues) throws IOException
http://
,
https://
or /
, then the request context path will be prepended, otherwise it will be
the unmodified redirect URL. So, when redirecting to another page in the same web application, always specify the
full path from the context root on (which in turn does not need to start with /
).
Faces.redirect("other.xhtml");
You can use String.format(String, Object...)
placeholder %s
in the redirect URL to represent
placeholders for any request parameter values which needs to be URL-encoded. Here's a concrete example:
Faces.redirect("other.xhtml?foo=%s&bar=%s", foo, bar);
This method implicitly also calls Flash.setRedirect(boolean)
with true
so that any flash
scoped attributes will survive the redirect.
url
- The URL to redirect the current response to.paramValues
- The request parameter values which you'd like to put URL-encoded in the given URL.IOException
- Whenever something fails at I/O level. The caller should preferably not catch it, but just
redeclare it in the action method. The servletcontainer will handle it.NullPointerException
- When url is null
.ExternalContext.redirect(String)
public static void redirectPermanent(String url, String... paramValues)
http://
,
https://
or /
, then the request context path will be prepended, otherwise it will be
the unmodified redirect URL. So, when redirecting to another page in the same web application, always specify the
full path from the context root on (which in turn does not need to start with /
).
Faces.redirectPermanent("other.xhtml");
You can use String.format(String, Object...)
placeholder %s
in the redirect URL to represent
placeholders for any request parameter values which needs to be URL-encoded. Here's a concrete example:
Faces.redirectPermanent("other.xhtml?foo=%s&bar=%s", foo, bar);
This method implicitly also calls Flash.setRedirect(boolean)
with true
so that any flash
scoped attributes will survive the redirect.
This method does by design not work on ajax requests. It is not possible to return a "permanent redirect" via JSF ajax XML response.
url
- The URL to redirect the current response to.paramValues
- The request parameter values which you'd like to put URL-encoded in the given URL.NullPointerException
- When url is null
.ExternalContext.setResponseStatus(int)
,
ExternalContext.setResponseHeader(String, String)
public static void responseSendError(int status, String message) throws IOException
<error-page>
whose <error-code>
matches the given status, or in a servlet
container specific default error page if there is none. The message will be available in the error page as a
request attribute with name javax.servlet.error.message
. The FacesContext.responseComplete()
will implicitly be called after sending the error.status
- The HTTP response status which is supposed to be in the range 4nn-5nn. You can use the constant
field values of HttpServletResponse
for this.message
- The message which is supposed to be available in the error page.IOException
- Whenever something fails at I/O level. The caller should preferably not catch it, but just
redeclare it in the action method. The servletcontainer will handle it.ExternalContext.responseSendError(int, String)
public static void addResponseHeader(String name, String value)
name
- The header name.value
- The header value.ExternalContext.addResponseHeader(String, String)
public static boolean isResponseCommitted()
true
if the response is already committed, otherwise false
.ExternalContext.isResponseCommitted()
public static void responseReset()
IllegalStateException
- When the response is already committed.ExternalContext.responseReset()
public static void renderResponse()
FacesContext.renderResponse()
public static boolean isRenderResponse()
true
if we're currently in the render response phase. This explicitly checks the current
phase ID instead of FacesContext.getRenderResponse()
as the latter may unexpectedly return false during
a GET request when <f:viewParam>
is been used.true
if we're currently in the render response phase.FacesContext.getCurrentPhaseId()
public static void responseComplete()
FacesContext.responseComplete()
public static boolean isResponseComplete()
true
if the FacesContext.responseComplete()
has been called.true
if the FacesContext.responseComplete()
has been called.FacesContext.responseComplete()
public static void login(String username, String password) throws ServletException
username
- The login username.password
- The login password.ServletException
- When the login is invalid, or when container managed FORM based authentication is not
enabled.HttpServletRequest.login(String, String)
public static boolean authenticate() throws ServletException, IOException
true
if the authentication was successful, otherwise false
.ServletException
- When the authentication has failed. The caller is responsible for handling it.IOException
- Whenever something fails at I/O level. The caller should preferably not catch it, but just
redeclare it in the action method. The servletcontainer will handle it.HttpServletRequest.authenticate(HttpServletResponse)
public static void logout() throws ServletException
invalidateSession()
instead. Note
that the user principal is still present in the response of the current request, it's therefore recommend to
send a redirect after logout()
or invalidateSession()
. You can use
redirect(String, String...)
for this.ServletException
- When the logout has failed.HttpServletRequest.logout()
public static String getRemoteUser()
ExternalContext.getRemoteUser()
public static boolean isUserInRole(String role)
role
- The role to be checked on the currently logged-in user.true
if the currently logged-in user has the given role, otherwise false
.ExternalContext.isUserInRole(String)
public static String getRequestCookie(String name)
name
- The HTTP request cookie name.UnsupportedOperationException
- When this platform does not support UTF-8.ExternalContext.getRequestCookieMap()
public static void addResponseCookie(String name, String value, int maxAge)
name
- The cookie name.value
- The cookie value.maxAge
- The maximum age of the cookie, in seconds. If this is 0
, then the cookie will be
removed. Note that the name and path must be exactly the same as it was when the cookie was created. If this is
-1
then the cookie will become a session cookie and thus live as long as the established HTTP
session.UnsupportedOperationException
- When this platform does not support UTF-8.ExternalContext.addResponseCookie(String, String, Map)
public static void addResponseCookie(String name, String value, String path, int maxAge)
name
- The cookie name.value
- The cookie value.path
- The cookie path. If this is /
, then the cookie is available in all pages of the webapp.
If this is /somespecificpath
, then the cookie is only available in pages under the specified path.maxAge
- The maximum age of the cookie, in seconds. If this is 0
, then the cookie will be
removed. Note that the name and path must be exactly the same as it was when the cookie was created. If this is
-1
then the cookie will become a session cookie and thus live as long as the established HTTP
session.UnsupportedOperationException
- When this platform does not support UTF-8.ExternalContext.addResponseCookie(String, String, Map)
public static void addResponseCookie(String name, String value, String domain, String path, int maxAge)
name
- The cookie name.value
- The cookie value.domain
- The cookie domain. You can use .example.com
(with a leading period) if you'd like the
cookie to be available to all subdomains of the domain. Note that you cannot set it to a different domain.path
- The cookie path. If this is /
, then the cookie is available in all pages of the webapp.
If this is /somespecificpath
, then the cookie is only available in pages under the specified path.maxAge
- The maximum age of the cookie, in seconds. If this is 0
, then the cookie will be
removed. Note that the name and path must be exactly the same as it was when the cookie was created. If this is
-1
then the cookie will become a session cookie and thus live as long as the established HTTP
session.UnsupportedOperationException
- When this platform does not support UTF-8.ExternalContext.addResponseCookie(String, String, Map)
public static void removeResponseCookie(String name, String path)
name
- The cookie name.path
- The cookie path.ExternalContext.addResponseCookie(String, String, Map)
public static HttpSession getSession()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
ExternalContext.getSession(boolean)
public static HttpSession getSession(boolean create)
create
argument is
true
, otherwise don't create one and return null
.
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
create
- Whether or not to create a new session if one doesn't exist.ExternalContext.getSession(boolean)
public static String getSessionId()
HttpSession.getId()
public static void invalidateSession()
ExternalContext.invalidateSession()
public static boolean hasSession()
true
if the HTTP session has already been created, otherwise false
.ExternalContext.getSession(boolean)
public static boolean isSessionNew()
false
when there is no means of a HTTP session.true
if the HTTP session has been created for the first time in the current request,
otherwise false
.ExternalContext.getSession(boolean)
,
HttpSession.isNew()
public static long getSessionCreationTime()
HttpSession.getCreationTime()
public static long getSessionLastAccessedTime()
HttpSession.getLastAccessedTime()
public static int getSessionMaxInactiveInterval()
HttpSession.getMaxInactiveInterval()
public static void setSessionMaxInactiveInterval(int seconds)
seconds
- The HTTP session timeout in seconds.HttpSession.setMaxInactiveInterval(int)
public static boolean hasSessionTimedOut()
true
if the HTTP session has been timed out for the current request, otherwise
false
.HttpServletRequest.getRequestedSessionId()
,
HttpServletRequest.isRequestedSessionIdValid()
public static ServletContext getServletContext()
Note that whenever you absolutely need this method to perform a general task, you might want to consider to submit a feature request to OmniFaces in order to add a new utility method which performs exactly this general task.
ExternalContext.getContext()
public static Map<String,String> getInitParameterMap()
<context-param>
entries in in web.xml
.ExternalContext.getInitParameterMap()
public static String getInitParameter(String name)
<param-value>
of a
<context-param>
in web.xml
associated with the given
<param-name>
.name
- The application initialization parameter name.null
if
there is none.ExternalContext.getInitParameter(String)
public static String getMimeType(String name)
<mime-mapping>
entries in web.xml
. When the mime type is
unknown, then a default of application/octet-stream
will be returned.name
- The file name to return the mime type for.ExternalContext.getMimeType(String)
public static URL getResource(String path) throws MalformedURLException
null
.path
- The application resource path to return an input stream for.MalformedURLException
- When the specified path is not in correct URL form.ExternalContext.getResource(String)
public static InputStream getResourceAsStream(String path)
null
.path
- The application resource path to return an input stream for.ExternalContext.getResourceAsStream(String)
public static Set<String> getResourcePaths(String path)
path
- The partial application resource path used to return matching resource paths.ExternalContext.getResourcePaths(String)
public static String getRealPath(String webContentPath)
/index.xhtml
) to an absolute disk file system path (e.g.
/path/to/server/work/folder/some.war/index.xhtml
) which can then be used in File
,
FileInputStream
, etc.
Note that this will return null
when the WAR is not expanded into the disk file system, but instead
into memory. If all you want is just an InputStream
of the web content resource, then better use
getResourceAsStream(String)
instead.
Also note that it wouldn't make sense to modify or create files in this location, as those changes would get lost anyway when the WAR is redeployed or even when the server is restarted. This is thus absolutely not a good location to store for example uploaded files.
webContentPath
- The web content path to be converted to an absolute disk file system path.public static Map<String,Object> getRequestMap()
ExternalContext.getRequestMap()
public static <T> T getRequestAttribute(String name)
T
- The expected return type.name
- The request scope attribute name.ClassCastException
- When T
is of wrong type.ExternalContext.getRequestMap()
public static void setRequestAttribute(String name, Object value)
name
- The request scope attribute name.value
- The request scope attribute value.ExternalContext.getRequestMap()
public static <T> T removeRequestAttribute(String name)
T
- The expected return type.name
- The request scope attribute name.null
if
there is no such attribute.ClassCastException
- When T
is of wrong type.ExternalContext.getRequestMap()
public static Flash getFlash()
Flash
implements Map<String, Object>
, so you
can just treat it like a Map<String, Object>
.ExternalContext.getFlash()
public static <T> T getFlashAttribute(String name)
T
- The expected return type.name
- The flash scope attribute name.ClassCastException
- When T
is of wrong type.ExternalContext.getFlash()
public static void setFlashAttribute(String name, Object value)
name
- The flash scope attribute name.value
- The flash scope attribute value.ExternalContext.getFlash()
public static <T> T removeFlashAttribute(String name)
T
- The expected return type.name
- The flash scope attribute name.null
if
there is no such attribute.ClassCastException
- When T
is of wrong type.ExternalContext.getFlash()
public static Map<String,Object> getViewMap()
UIViewRoot.getViewMap()
public static <T> T getViewAttribute(String name)
T
- The expected return type.name
- The view scope attribute name.ClassCastException
- When T
is of wrong type.UIViewRoot.getViewMap()
public static void setViewAttribute(String name, Object value)
name
- The view scope attribute name.value
- The view scope attribute value.UIViewRoot.getViewMap()
public static <T> T removeViewAttribute(String name)
T
- The expected return type.name
- The view scope attribute name.null
if
there is no such attribute.ClassCastException
- When T
is of wrong type.UIViewRoot.getViewMap()
public static Map<String,Object> getSessionMap()
ExternalContext.getSessionMap()
public static <T> T getSessionAttribute(String name)
T
- The expected return type.name
- The session scope attribute name.ClassCastException
- When T
is of wrong type.ExternalContext.getSessionMap()
public static void setSessionAttribute(String name, Object value)
name
- The session scope attribute name.value
- The session scope attribute value.ExternalContext.getSessionMap()
public static <T> T removeSessionAttribute(String name)
T
- The expected return type.name
- The session scope attribute name.null
if
there is no such attribute.ClassCastException
- When T
is of wrong type.ExternalContext.getSessionMap()
public static Map<String,Object> getApplicationMap()
ExternalContext.getApplicationMap()
public static <T> T getApplicationAttribute(String name)
T
- The expected return type.name
- The application scope attribute name.ClassCastException
- When T
is of wrong type.ExternalContext.getApplicationMap()
public static void setApplicationAttribute(String name, Object value)
name
- The application scope attribute name.value
- The application scope attribute value.ExternalContext.getApplicationMap()
public static <T> T removeApplicationAttribute(String name)
T
- The expected return type.name
- The application scope attribute name.null
if
there is no such attribute.ClassCastException
- When T
is of wrong type.ExternalContext.getApplicationMap()
public static void sendFile(File file, boolean attachment) throws IOException
FacesContext.responseComplete()
will implicitly be called
after successful streaming.file
- The file to be sent to the response.attachment
- Whether the file should be provided as attachment, or just inline.IOException
- Whenever something fails at I/O level. The caller should preferably not catch it, but just
redeclare it in the action method. The servletcontainer will handle it.public static void sendFile(byte[] content, String filename, boolean attachment) throws IOException
FacesContext.responseComplete()
will
implicitly be called after successful streaming.content
- The file content as byte array.filename
- The file name which should appear in content disposition header.attachment
- Whether the file should be provided as attachment, or just inline.IOException
- Whenever something fails at I/O level. The caller should preferably not catch it, but just
redeclare it in the action method. The servletcontainer will handle it.public static void sendFile(InputStream content, String filename, boolean attachment) throws IOException
InputStream.close()
will implicitly be called after streaming, regardless of whether an exception is
been thrown or not. The FacesContext.responseComplete()
will implicitly be called after successful
streaming.content
- The file content as input stream.filename
- The file name which should appear in content disposition header.attachment
- Whether the file should be provided as attachment, or just inline.IOException
- Whenever something fails at I/O level. The caller should preferably not catch it, but just
redeclare it in the action method. The servletcontainer will handle it.Copyright © 2012–2015 OmniFaces. All rights reserved.