Class WApplication
- java.lang.Object
-
- eu.webtoolkit.jwt.WObject
-
- eu.webtoolkit.jwt.WApplication
-
public class WApplication extends WObject
Represents an application instance for a single session.Each user session of your application has a corresponding WApplication instance. You need to create a new instance and return it as the result of
WtServlet.createApplication(WEnvironment). The instance is the main entry point to session information, and holds a reference to thegetRoot()of the widget tree.The recipe for a JWt web application, which allocates new
WApplicationinstances for every user visiting the application is thus:public class HelloServlet extends WtServlet { public HelloServlet() { super(); } public WApplication createApplication(WEnvironment env) { // In practice, you will specialize WApplication and simply // return a new instance. WApplication app = new WApplication(env); app.getRoot().addWidget(new WText("Hello world.")); return app; } }Throughout the session, the instance is available through the static method
getInstance(), which uses thread-specific storage to keep track of the current session. The application may be exited either using the methodquit(), or because of a timeout after the user has closed the window, but not because the user does not interact: keep-alive messages in the background will keep the session around as long as the user has the page opened.The WApplication object provides access to session-wide settings, including:
- circumstantial information through
getEnvironment(), which gives details about the user, start-up arguments, and user agent capabilities. - the application title with
setTitle(). - inline and external style sheets using
getStyleSheet()anduseStyleSheet(). - inline and external JavaScript using
doJavaScript()andrequire(). - the top-level widget in
getRoot(), representing the entire browser window, or multiple top-level widgets usingbindWidget()when deployed inEntryPointType.WidgetSetmode to manage a number of widgets within a 3rd party page. - definition of cookies using
setCookie()to persist information across sessions, which may be read usingWEnvironment#getCookie()in a future session. - management of the internal path (that enables browser history and bookmarks) using
setInternalPath()and related methods. - support for server-initiated updates with
enableUpdates() - localization information and message resources bundles, with
setLocale()andsetLocalizedStrings()
- circumstantial information through
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classWApplication.UpdateLockA synchronization lock for manipulating and updating the application and its widgets outside of the event loop.-
Nested classes/interfaces inherited from class eu.webtoolkit.jwt.WObject
WObject.FormData
-
-
Constructor Summary
Constructors Constructor Description WApplication(WEnvironment env)Creates a new application instance.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddAutoJavaScript(java.lang.String javascript)Adds JavaScript statements that should be run continuously.voidaddGlobalWidget(WWidget w)voidaddMetaHeader(MetaHeaderType type, java.lang.String name, java.lang.CharSequence content)Adds an HTML meta header.voidaddMetaHeader(MetaHeaderType type, java.lang.String name, java.lang.CharSequence content, java.lang.String lang)Adds an HTML meta header.voidaddMetaHeader(java.lang.String name, java.lang.CharSequence content)Adds a "name" HTML meta header.voidaddMetaHeader(java.lang.String name, java.lang.CharSequence content, java.lang.String lang)Adds a "name" HTML meta header.voidaddMetaLink(java.lang.String href, java.lang.String rel, java.lang.String media, java.lang.String hreflang, java.lang.String type, java.lang.String sizes, boolean disabled)Adds an HTML meta link.voidattachThread()Attach an auxiliary thread to this application.voidattachThread(boolean attach)Attach an auxiliary thread to this application.voidbindWidget(WWidget widget, java.lang.String domId)Binds a top-level widget for aEntryPointType.WidgetSetdeployment.voiddeclareJavaScriptFunction(java.lang.String name, java.lang.String function)Declares an application-wide JavaScript function.voiddestroy()Destroys the application session.voiddoJavaScript(java.lang.String javascript)Executes some JavaScript code.voiddoJavaScript(java.lang.String javascript, boolean afterLoaded)Executes some JavaScript code.protected voidenableAjax()Progresses to an Ajax-enabled user interface.voidenableUpdates()Enables server-initiated updates.voidenableUpdates(boolean enabled)Enables server-initiated updates.java.lang.StringencodeUntrustedUrl(java.lang.String url)Encodes an untrusted URL to prevent referer leaks.java.lang.StringfindAddedCookies(java.lang.String name)WWidgetfindWidget(java.lang.String name)Finds a widget by name.WStringgetBodyAttribute(java.lang.String name)Returns the current <body> element attribute value of the specifiedname.java.lang.StringgetBodyClass()Returns the style class set for the entire page <body>.java.lang.StringgetBookmarkUrl()Returns a bookmarkable URL for the current internal path.java.lang.StringgetBookmarkUrl(java.lang.String internalPath)Returns a bookmarkable URL for a given internal path.WXmlLocalizedStringsgetBuiltinLocalizedStrings()Accesses the built-in resource bundle.WStringgetCloseMessage()Returns the close message.WWebWidgetgetDomRoot()WEnvironmentgetEnvironment()Returns the environment information.WStringgetHtmlAttribute(java.lang.String name)Returns the current <html> element attribute value of the specifiedname.java.lang.StringgetHtmlClass()Returns the style class set for the entire page <html>.static WApplicationgetInstance()Returns the current application instance.java.lang.StringgetInternalPath()Returns the current internal path.java.lang.StringgetInternalPathNextPart(java.lang.String path)Returns a part of the current internal path.java.lang.StringgetJavaScriptClass()Returns the name of the application JavaScript class.LayoutDirectiongetLayoutDirection()Returns the layout direction.WLoadingIndicatorgetLoadingIndicator()Returns the loading indicator.java.util.LocalegetLocale()Returns the current locale.WLocalizedStringsgetLocalizedStrings()Returns the resource object that provides localized strings.longgetMaximumRequestSize()Returns the current maximum size of a request to the application.static java.lang.StringgetRelativeResourcesUrl()Returns the URL at which the resources are deployed.static java.lang.StringgetResourcesUrl()Returns the URL at which the resources are deployed.WContainerWidgetgetRoot()Returns the root container.eu.webtoolkit.jwt.ServerSideFontMetricsgetServerSideFontMetrics()Returns the font metrics for server-side rendering.java.lang.StringgetSessionId()Returns the unique identifier for the current session.WCssStyleSheetgetStyleSheet()Returns a reference to the inline style sheet.WThemegetTheme()Returns the theme.WStringgetTitle()Returns the window title.WApplication.UpdateLockgetUpdateLock()Grabs and returns the lock for manipulating widgets outside the event loop.EventSignalglobalEnterPressed()Event signal emitted when enter was pressed.EventSignalglobalEscapePressed()Event signal emitted when escape was pressed.EventSignal1<WKeyEvent>globalKeyPressed()Event signal emitted when a "character" was entered.EventSignal1<WKeyEvent>globalKeyWentDown()Event signal emitted when a keyboard key is pushed down.EventSignal1<WKeyEvent>globalKeyWentUp()Event signal emitted when a keyboard key is released.protected voidhandleJavaScriptError(java.lang.String errorText)handleJavaScriptError print javaScript errors to log file.booleanhasQuit()Returns whether the application has quit.protected voididleTimeout()Idle timeout handler.Signal1<java.lang.String>internalPathChanged()Signal which indicates that the user changes the internal path.Signal1<java.lang.String>internalPathInvalid()Signal which indicates that an invalid internal path is navigated.booleaninternalPathMatches(java.lang.String path)Checks if the internal path matches a given path.java.lang.StringinternalSubPath(java.lang.String path)booleanisCustomJQuery()protected booleanisExposed(WWidget w)Returns whether a widget is exposed in the interface.booleanisInternalPathDefaultValid()Returns whether an internal path is valid by default.booleanisInternalPathValid()Returns whether the current internal path is valid.booleanisUpdatesEnabled()Returns whether server-initiated updates are enabled.voidloadJavaScript(java.lang.String jsFile, WJavaScriptPreamble preamble)Loads an internal JavaScript file.java.lang.StringmakeAbsoluteUrl(java.lang.String url)Makes an absolute URL.WStringmetaHeader(MetaHeaderType type, java.lang.String name)Returns a meta header value.protected voidnotify(WEvent e)Notifies an event to the application.static booleanpathMatches(java.lang.String path, java.lang.String query)Utility function to check if one path falls under another path.voidprocessEvents()Processes UI events.voidquit()Quits the application.voidquit(java.lang.CharSequence restartMessage)Quits the application.static java.lang.StringreadConfigurationProperty(java.lang.String name, java.lang.String value)Reads a configuration property.voidredirect(java.lang.String url)Redirects the application to another location.voidrefresh()Refreshes the application.voidremoveCookie(jakarta.servlet.http.Cookie cookie)Removes a cookie.voidremoveCookie(java.lang.String name)Removes a cookie.voidremoveCookie(java.lang.String name, java.lang.String domain)Removes a cookie.voidremoveCookie(java.lang.String name, java.lang.String domain, java.lang.String path)Deprecated.UseremoveCookie()instead.voidremoveGlobalWidget(WWidget w)voidremoveMetaHeader(MetaHeaderType type)Removes one or all meta headers.voidremoveMetaHeader(MetaHeaderType type, java.lang.String name)Removes one or all meta headers.voidremoveMetaLink(java.lang.String href)Removes the HTML meta link.voidremoveStyleSheet(WLink link)Removes an external stylesheet.Signal1<java.lang.Long>requestTooLarge()Signal which indicates that too a large request was received.booleanrequire(java.lang.String uri)Loads a JavaScript library.booleanrequire(java.lang.String uri, java.lang.String symbol)Loads a JavaScript library.booleanrequireJQuery(java.lang.String uri)java.lang.StringresolveRelativeUrl(java.lang.String url)"Resolves" a relative URL taking into account internal paths.voidsetBodyAttribute(java.lang.String name, java.lang.String value)Sets an attribute for the entire page <body> element.voidsetBodyClass(java.lang.String styleClass)Sets a style class to the entire page <body>.voidsetConfirmCloseMessage(java.lang.CharSequence message)Sets the message for the user to confirm closing of the application window/tab.voidsetCookie(jakarta.servlet.http.Cookie cookie)Sets a new cookie.voidsetCookie(java.lang.String name, java.lang.String value, int maxAge)Sets a new cookie.voidsetCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain)Sets a new cookie.voidsetCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain, java.lang.String path)Sets a new cookie.voidsetCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain, java.lang.String path, boolean secure)Deprecated.UsesetCookie()instead.voidsetCssTheme(java.lang.String theme)Sets a CSS theme.voidsetFocus(java.lang.String id, int selectionStart, int selectionEnd)voidsetHtmlAttribute(java.lang.String name, java.lang.String value)Sets an attribute for the entire page <html> element.voidsetHtmlClass(java.lang.String styleClass)Sets a style class to the entire page <html>.voidsetInternalPath(java.lang.String path)Changes the internal path.voidsetInternalPath(java.lang.String path, boolean emitChange)Changes the internal path.voidsetInternalPathDefaultValid(boolean valid)Sets whether an internal path is valid by default.voidsetInternalPathValid(boolean valid)Sets whether the current internal path is valid.voidsetJavaScriptClass(java.lang.String javaScriptClass)Sets the name of the application JavaScript class.voidsetLayoutDirection(LayoutDirection direction)Sets the layout direction.voidsetLoadingIndicator(WLoadingIndicator indicator)Sets the loading indicator.voidsetLocale(java.util.Locale locale)Changes the locale.voidsetLocale(java.util.Locale locale, boolean doRefresh)Changes the locale.voidsetLocalizedStrings(WLocalizedStrings translator)Sets the resource object that provides localized strings.voidsetTheme(WTheme theme)Sets the theme.voidsetTitle(java.lang.CharSequence title)Sets the window title.voidsetTwoPhaseRenderingThreshold(int bytes)Changes the threshold for two-phase rendering.voidsuspend(java.time.Duration duration)Suspend the application.voidtriggerUpdate()Propagates server-initiated updates.protected voidunload()Handles a browser unload event.Signalunsuspended()Signalthat is emitted when the application is no longer suspended.java.lang.Stringurl()Returns a URL for the current session.java.lang.Stringurl(java.lang.String internalPath)Returns a URL for the current session.voiduseStyleSheet(WLink link)Adds an external style sheet.voiduseStyleSheet(WLinkedCssStyleSheet styleSheet)Adds an external stylesheet.voiduseStyleSheet(WLinkedCssStyleSheet styleSheet, java.lang.String condition)Adds an external stylesheet.voiduseStyleSheet(WLink link, java.lang.String media)Adds an external style sheet.voiduseStyleSheet(WLink link, java.lang.String condition, java.lang.String media)Conditionally adds an external style sheet.voidwaitForEvent()Blocks the thread, waiting for an UI event.-
Methods inherited from class eu.webtoolkit.jwt.WObject
getId, getObjectName, remove, setFormData, setObjectName, tr
-
-
-
-
Constructor Detail
-
WApplication
public WApplication(WEnvironment env)
Creates a new application instance.The
environmentprovides information on the initial request, user agent, and deployment-related information.
-
-
Method Detail
-
getInstance
public static WApplication getInstance()
Returns the current application instance.This method uses thread-specific storage to fetch the current session.
-
getEnvironment
public WEnvironment getEnvironment()
Returns the environment information.This method returns the environment object that was used when constructing the application. The environment provides information on the initial request, user agent, and deployment-related information.
- See Also:
url(String internalPath),getSessionId()
-
getRoot
public WContainerWidget getRoot()
Returns the root container.This is the top-level widget container of the application, and corresponds to entire browser window. The user interface of your application is represented by the content of this container.
The
getRoot()widget is only defined when the application manages the entire window. When deployed as aEntryPointType.WidgetSetapplication, there is no root() container, andnullis returned. Instead, usebindWidget()to bind one or more root widgets to existing HTML <div> (or other) elements on the page.
-
findWidget
public WWidget findWidget(java.lang.String name)
Finds a widget by name.This finds a widget in the application's widget hierarchy. It does not only consider widgets in the
getRoot(), but also widgets that are placed outside this root, such as in dialogs, or other "roots" such as all the bound widgets in a widgetset application.
-
getStyleSheet
public WCssStyleSheet getStyleSheet()
Returns a reference to the inline style sheet.Widgets may allow configuration of their look and feel through style classes. These may be defined in this inline stylesheet, or in external style sheets.
It is usually preferable to use external stylesheets (and consider more accessible). Still, the internal stylesheet has as benefit that style rules may be dynamically updated, and it is easier to manage logistically.
-
useStyleSheet
public void useStyleSheet(WLink link, java.lang.String media)
Adds an external style sheet.The
linkis a link to a stylesheet.The
mediaindicates the CSS media to which this stylesheet applies. This may be a comma separated list of media. The default value is "all" indicating all media.This is an overloaded method for convenience, equivalent to:
useStyleSheet(Wt::WCssStyleSheet(link, media))
-
useStyleSheet
public final void useStyleSheet(WLink link)
Adds an external style sheet.
-
useStyleSheet
public void useStyleSheet(WLink link, java.lang.String condition, java.lang.String media)
Conditionally adds an external style sheet.This is an overloaded method for convenience, equivalent to:
useStyleSheet(Wt::WLinkedCssStyleSheet(link, media), condition)
-
useStyleSheet
public void useStyleSheet(WLinkedCssStyleSheet styleSheet, java.lang.String condition)
Adds an external stylesheet.Widgets may allow configuration of their look and feel through style classes. These may be defined in an inline stylesheet, or in external style sheets.
External stylesheets are inserted after the internal style sheet, and can therefore override default styles set by widgets in the internal style sheet. External stylesheets must have valid link.
If not empty,
conditionis a string that is used to apply the stylesheet to specific versions of IE. Only a limited subset of the IE conditional comments syntax is supported (since these are in fact interpreted server-side instead of client-side). Examples are:- "IE gte 6": only for IE version 6 or later.
- "!IE gte 6": only for IE versions prior to IE6.
- "IE lte 7": only for IE versions prior to IE7.
-
useStyleSheet
public final void useStyleSheet(WLinkedCssStyleSheet styleSheet)
Adds an external stylesheet.
-
removeStyleSheet
public void removeStyleSheet(WLink link)
Removes an external stylesheet.
-
setTheme
public void setTheme(WTheme theme)
Sets the theme.The theme provides the look and feel of several built-in widgets, using CSS style rules. Rules for each theme are defined in the
resources/themes/theme/folder.The default theme is "default" CSS theme.
-
getTheme
public WTheme getTheme()
Returns the theme.
-
setCssTheme
public void setCssTheme(java.lang.String theme)
Sets a CSS theme.This sets a
WCssThemeas theme.The theme provides the look and feel of several built-in widgets, using CSS style rules. Rules for each CSS theme are defined in the
resources/themes/name/folder.The default theme is "default". Setting an empty theme "" will result in a stub CSS theme that does not load any stylesheets.
-
setLayoutDirection
public void setLayoutDirection(LayoutDirection direction)
Sets the layout direction.The default direction is
LayoutDirection.LeftToRight.This sets the language text direction, which by itself sets the default text alignment and reverse the column orders of <table> elements.
In addition, JWt will take this setting into account in
WTextEdit,WTableViewandWTreeView(so that columns are reverted), and swap the behaviour ofWWidget#setFloatSide()andWWidget#setOffsets()forLayoutDirection.RightToLeftlanguages. Note that CSS settings themselves are not affected by this setting, and thus for example"float: right"will move a box to the right, irrespective of the layout direction.The library sets
"Wt-ltr"or"Wt-rtl"as style classes for the document body. You may use this if to override certain style rules for a Right-to-Left document.The only valid values are
LayoutDirection.LeftToRightorLayoutDirection.RightToLeft.For example:
body .sidebar { float: right; } body.Wt-rtl .sidebar { float: left; }Note: The layout direction can be set only at application startup and does not have the effect of rerendering the entire UI.
-
getLayoutDirection
public LayoutDirection getLayoutDirection()
Returns the layout direction.
-
setBodyClass
public void setBodyClass(java.lang.String styleClass)
Sets a style class to the entire page <body>.- See Also:
setHtmlClass(String styleClass)
-
getBodyClass
public java.lang.String getBodyClass()
Returns the style class set for the entire page <body>.- See Also:
setBodyClass(String styleClass)
-
setHtmlClass
public void setHtmlClass(java.lang.String styleClass)
Sets a style class to the entire page <html>.- See Also:
setBodyClass(String styleClass)
-
getHtmlClass
public java.lang.String getHtmlClass()
Returns the style class set for the entire page <html>.- See Also:
setHtmlClass(String styleClass)
-
setHtmlAttribute
public void setHtmlAttribute(java.lang.String name, java.lang.String value)Sets an attribute for the entire page <html> element.This allows you to set any of the global attributes (see: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes) on the <html> tag. As well as any tags specific to that tag (see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html).
Note: If the
valuecontains more complex JavaScript, make sure that"and'are properly escaped. Otherwise you may encounter JavaScript errors.Note: This can control the <html>'s
class,dir, andlangas well, but this should generally be avoided, since the application manages that separately.
-
getHtmlAttribute
public WString getHtmlAttribute(java.lang.String name)
Returns the current <html> element attribute value of the specifiedname.
-
setBodyAttribute
public void setBodyAttribute(java.lang.String name, java.lang.String value)Sets an attribute for the entire page <body> element.This allows you to set any of the global attributes (see: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes) on the <body> tag. As well as any tags specific to that tag (see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body).
Note: If the
valuecontains more complex JavaScript, make sure that"and'are properly escaped. Otherwise you may encounter JavaScript errors.
-
getBodyAttribute
public WString getBodyAttribute(java.lang.String name)
Returns the current <body> element attribute value of the specifiedname.
-
setTitle
public void setTitle(java.lang.CharSequence title)
Sets the window title.Sets the browser window title to
title.The default title is "".
- See Also:
getTitle()
-
getTitle
public WString getTitle()
Returns the window title.- See Also:
setTitle(CharSequence title)
-
getCloseMessage
public WString getCloseMessage()
Returns the close message.
-
getLocalizedStrings
public WLocalizedStrings getLocalizedStrings()
Returns the resource object that provides localized strings.This returns the object previously set using
setLocalizedStrings().WString#tr()is used to create localized strings, whose localized translation is looked up through this object, using a key.- See Also:
WString.tr(String key)
-
getBuiltinLocalizedStrings
public WXmlLocalizedStrings getBuiltinLocalizedStrings()
Accesses the built-in resource bundle.This is an internal function and should not be called directly.
- See Also:
getLocalizedStrings()
-
setLocalizedStrings
public void setLocalizedStrings(WLocalizedStrings translator)
Sets the resource object that provides localized strings.The
translatorresolves localized strings within the current application locale.- See Also:
getLocalizedStrings(),WString.tr(String key)
-
setLocale
public void setLocale(java.util.Locale locale, boolean doRefresh)Changes the locale.The locale is used by the localized strings resource to resolve localized strings.
By passing an empty
locale, the default locale is chosen.By default, when the locale is changed,
refresh()is called, which will resolve the strings of the current user-interface in the new locale. This can be changed by having thedoRefreshparameter set tofalse.At construction, the locale is copied from the environment (
WEnvironment.getLocale()), and this is the locale that was configured by the user in his browser preferences, and passed using an HTTP request header.- See Also:
getLocalizedStrings(),WString.tr(String key)
-
setLocale
public final void setLocale(java.util.Locale locale)
Changes the locale.Calls
setLocale(locale, true)
-
getLocale
public java.util.Locale getLocale()
Returns the current locale.
-
refresh
public void refresh()
Refreshes the application.This lets the application refresh its data, including strings from message resource bundles. This is done by propagating
WWidget.refresh()through the widget hierarchy.This method is also called when the user hits the refresh (or reload) button, if this can be caught within the current session.
The reload button may only be caught when cookies for session tracking are configured in the servlet container.
- See Also:
WWidget.refresh()
-
bindWidget
public void bindWidget(WWidget widget, java.lang.String domId)
Binds a top-level widget for aEntryPointType.WidgetSetdeployment.This method binds a
widgetto an existing element with DOM iddomIdon the page. The element type should correspond with the widget type (e.g. it should be a <div> for aWContainerWidget, or a <table> for aWTable).- See Also:
getRoot(),EntryPointType.WidgetSet
-
url
public java.lang.String url(java.lang.String internalPath)
Returns a URL for the current session.Returns the (relative) URL for this application session (including the session ID if necessary). The URL includes the full application path, and is expanded by the browser into a full URL.
For example, for an application deployed at
this method might returnhttp://www.mydomain.com/stuff/app.wt"/stuff/app.wt?wtd=AbCdEf". Additional query parameters can be appended in the form of"¶m1=value¶m2=value".To obtain a URL that is suitable for bookmarking the current application state, to be used across sessions, use
getBookmarkUrl()instead.
-
url
public final java.lang.String url()
Returns a URL for the current session.Returns
url("")
-
makeAbsoluteUrl
public java.lang.String makeAbsoluteUrl(java.lang.String url)
Makes an absolute URL.Returns an absolute URL for a given (relative url) by including the schema, hostname, and deployment path.
If
urlis "", then the absolute base URL is returned. This is the absolute URL at which the application is deployed, up to the last '/'.The default implementation is not complete: it does not handle relative URL path segments with '..'. It just handles the cases that are necessary for JWt.
This is not used in the library, except when a public URL is needed, e.g. for inclusion in an email.
You may want to reimplement this method when the application is hosted behind a reverse proxy or in general the public URL of the application cannot be guessed correctly by the application.
-
resolveRelativeUrl
public java.lang.String resolveRelativeUrl(java.lang.String url)
"Resolves" a relative URL taking into account internal paths.This resolves the relative URL against the base path of the application, so that it will point to the correct path regardless of the current internal path, e.g. if the application is deployed at
http://example.com/oneand we're at the internal path/two/, so that the full URL ishttp://example.com/one/two/, the output of the input URLthreewill point tohttp://example.com/three, and nothttp://example.com/one/two/three.If the given url is the empty string, the result will point to the base path of the application.
See the table below for more examples.
When you would want to use resolveRelativeUrl:
Using HTML5 History API or in a plain HTML session (without ugly internal paths), the internal path is present as a full part of the URL. This has a consequence that relative URLs, if not dealt with, would be resolved against the last 'folder' name of the internal path, rather than against the application deployment path (which is what you probably want).
When using a widgetset mode deployment, or when configuring a baseURL property in the configuration, this method will make an absolute URL so that the property is fetched from the right server.
Otherwise, this method will fixup a relative URL so that it resolves correctly against the base path of an application. This does not necessarily mean that the URL is resolved into an absolute URL. In fact, JWt will simply prepend a sequence of "../" path elements to correct for the internal path. When passed an absolute URL (i.e. starting with '/'), the url is returned unchanged.
For URLs passed to the JWt API (and of which the library knows it represents a URL) this method is called internally by the library. But it may be useful for URLs which are set e.g. inside a
WTemplate.Examples
Note that whether the deployment path and entry point ends with a slash is significant. Below are some examples with the deployment path in red and the internal path in blue.
Current full path url argument Result points to http://example.com/foo/bar/internal/path
Deployment path:/foo/bar(no slash at the end)
Internal path:/internal/path(empty string) http://example.com/foo/bar.http://example.com/foo/./http://example.com/foo/../http://example.com/http://example.com/foo/bar/internal/path
Deployment path:/foo/bar/(with slash at the end)
Internal path:/internal/path
Note that the slash between the deployment path and the internal path is shared(empty string) http://example.com/foo/bar/.http://example.com/foo/bar/./http://example.com/foo/bar/../http://example.com/foo/
-
getBookmarkUrl
public java.lang.String getBookmarkUrl()
Returns a bookmarkable URL for the current internal path.Is equivalent to
bookmarkUrl(internalPath()), seegetBookmarkUrl().To obtain a URL that is refers to the current session of the application, use
url()instead.
-
getBookmarkUrl
public java.lang.String getBookmarkUrl(java.lang.String internalPath)
Returns a bookmarkable URL for a given internal path.Returns the (relative) URL for this application that includes the internal path
internalPath, usable across sessions.The returned URL concatenates the internal path to the application base URL, and when no JavaScript is available and URL rewriting is used for session-tracking, a session Id is appended to reuse an existing session if available.
You can use
getBookmarkUrl()as the destination for aWAnchor, and listen to a click event is attached to a slot that switches to the internal pathinternalPath(see WAnchor::setRefInternalPath()). In this way, an anchor can be used to switch between internal paths within an application regardless of the situation (browser with or without Ajax support, or a web spider bot), but still generates suitable URLs across sessions, which can be used for bookmarking, opening in a new window/tab, or indexing.To obtain a URL that refers to the current session of the application, use
url()instead.- See Also:
url(String internalPath),getBookmarkUrl()
-
setInternalPath
public void setInternalPath(java.lang.String path, boolean emitChange)Changes the internal path.A JWt application may manage multiple virtual paths. The virtual path is appended to the application URL. Depending on the situation, the path is directly appended to the application URL or it is appended using a name anchor (#).
For example, for an application deployed at:
for which anhttp://www.mydomain.com/stuff/app.wtinternalPath"/project/z3cbc/details/"is set, the two forms for the application URL are:- in an AJAX session (HTML5):
http://www.mydomain.com/stuff/app.wt/project/z3cbc/details/ - in an AJAX session (HTML4):
http://www.mydomain.com/stuff/app.wt#/project/z3cbc/details/ - in a plain HTML session:
http://www.mydomain.com/stuff/app.wt/project/z3cbc/details/
Note, since JWt 3.1.9, the actual form of the URL no longer affects relative URL resolution, since now JWt includes an HTML
meta basetag which points to the deployment path, regardless of the current internal path. This does break deployments behind a reverse proxy which changes paths.When the internal path is changed, an entry is added to the browser history. When the user navigates back and forward through this history (using the browser back/forward buttons), an
internalPathChanged()event is emitted. You should listen to this signal to switch the application to the corresponding state. WhenemitChangeistrue, this signal is also emitted by setting the path (but only if the path is actually changed).A url that includes the internal path may be obtained using
getBookmarkUrl().The
internalPathmust start with a '/'. In this way, you can still use normal anchors in your HTML. Internal path changes initiated in the browser to paths that do not start with a '/' are ignored.The
emitChangeparameter determines whether calling this method causes theinternalPathChanged()signal to be emitted.- See Also:
getBookmarkUrl(),getInternalPath(),internalPathChanged()
- in an AJAX session (HTML5):
-
setInternalPath
public final void setInternalPath(java.lang.String path)
Changes the internal path.
-
setInternalPathDefaultValid
public void setInternalPathDefaultValid(boolean valid)
Sets whether an internal path is valid by default.This configures how you treat (invalid) internal paths. If an internal path is treated valid by default then you need to call setInternalPath(false) for an invalid path. If on the other hand you treat an internal path as invalid by default, then you need to call setInternalPath(true) for a valid path.
A user which opens an invalid internal path will receive a HTTP 404-Not Found response code (if sent an HTML response).
The default value is
true.
-
isInternalPathDefaultValid
public boolean isInternalPathDefaultValid()
Returns whether an internal path is valid by default.
-
setInternalPathValid
public void setInternalPathValid(boolean valid)
Sets whether the current internal path is valid.You can use this function in response to an internal path change event (or at application startup) to indicate whether the new (or initial) internal path is valid. This has only an effect on plain HTML sessions, or on the first response in an application deployed with progressive bootstrap settings, as this generates then a 404 Not-Found response.
-
isInternalPathValid
public boolean isInternalPathValid()
Returns whether the current internal path is valid.- See Also:
setInternalPathValid(boolean valid)
-
getInternalPath
public java.lang.String getInternalPath()
Returns the current internal path.When the application is just created, this is equal to
WEnvironment.getInternalPath().
-
getInternalPathNextPart
public java.lang.String getInternalPathNextPart(java.lang.String path)
Returns a part of the current internal path.This is a convenience method which returns the next
folderin the internal path, after the givenpath.For example, when the current internal path is
"/project/z3cbc/details", this method returns"details"when called with"/project/z3cbc/"aspathargument.The
pathmust start with a '/', andinternalPathMatches()should evaluate totruefor the givenpath. If not, an empty string is returned and an error message is logged.- See Also:
getInternalPath(),internalPathChanged()
-
internalSubPath
public java.lang.String internalSubPath(java.lang.String path)
-
internalPathMatches
public boolean internalPathMatches(java.lang.String path)
Checks if the internal path matches a given path.Returns whether the current
getInternalPath()starts withpath(or is equal topath). You will typically use this method within a slot conneted to theinternalPathChanged()signal, to check that an internal path change affects the widget. It may also be useful before changingpathusingsetInternalPath()if you do not intend to remove sub paths when the current internal path already matchespath.The
pathmust start with a '/'.
-
internalPathChanged
public Signal1<java.lang.String> internalPathChanged()
Signal which indicates that the user changes the internal path.This signal indicates a change to the internal path, which is usually triggered by the user using the browser back/forward buttons.
The argument contains the new internal path.
-
internalPathInvalid
public Signal1<java.lang.String> internalPathInvalid()
Signal which indicates that an invalid internal path is navigated.
-
redirect
public void redirect(java.lang.String url)
Redirects the application to another location.The client will be redirected to a new location identified by
url. Use this in conjunction withquit()if you want the application to be terminated as well.Calling redirect() does not imply quit() since it may be useful to switch between a non-secure and secure (SSL) transport connection.
-
getResourcesUrl
public static java.lang.String getResourcesUrl()
Returns the URL at which the resources are deployed.Returns resolveRelativeUrl(relativeResourcesUrl())
-
getRelativeResourcesUrl
public static java.lang.String getRelativeResourcesUrl()
Returns the URL at which the resources are deployed.- See Also:
resolveRelativeUrl(String url)
-
getSessionId
public java.lang.String getSessionId()
Returns the unique identifier for the current session.The session id is a string that uniquely identifies the current session. Note that the actual contents has no particular meaning and client applications should in no way try to interpret its value.
-
enableUpdates
public void enableUpdates(boolean enabled)
Enables server-initiated updates.By default, updates to the user interface are possible only at startup, during any event (in a slot), or at regular time points using
WTimer. This is the normal JWt event loop.In some cases, one may want to modify the user interface from a second thread, outside the event loop. While this may be worked around by the
WTimer, in some cases, there are bandwidth and processing overheads associated which may be unnecessary, and which create a trade-off with time resolution of the updates.When
enabledistrue, this enables "server push" (what is called 'comet' in AJAX terminology). Widgets may then be modified, created or deleted outside of the event loop (e.g. in response to execution of another thread), and these changes are propagated by callingtriggerUpdate().Note that you need to grab the application's update lock to avoid concurrency problems, whenever you modify the application's state from another thread.
An example of how to modify the widget tree outside the event loop and propagate changes is:
// You need to have a reference to the application whose state // you are about to manipulate. WApplication app = ...; // Grab the application lock WApplication.UpdateLock lock = app.getUpdateLock(); try { // We now have exclusive access to the application: // we can safely modify the widget tree for example. app.getRoot().addWidget(new WText("Something happened!")); // Push the changes to the browser app.triggerUpdate(); } finally { lock.release(); }This works only if your servlet container supports the Servlet 3.0 API. If you try to invoke this function on a servlet container with no such support, an exception will be thrown.
Note: This works only if JavaScript is available on the client.
- See Also:
triggerUpdate()
-
enableUpdates
public final void enableUpdates()
Enables server-initiated updates.Calls
enableUpdates(true)
-
isUpdatesEnabled
public boolean isUpdatesEnabled()
Returns whether server-initiated updates are enabled.- See Also:
enableUpdates(boolean enabled)
-
triggerUpdate
public void triggerUpdate()
Propagates server-initiated updates.When the lock to the application is released, changes will propagate to the user interface. This call only has an effect after updates have been enabled from within the normal event loop using
enableUpdates().This is typically used only outside of the main event loop, e.g. from another thread or from within a method posted to an application using WServer::post(), since changes always propagate within the event loop at the end of the event.
The update is not immediate, and thus changes that happen after this call will equally be pushed to the client.
- See Also:
enableUpdates(boolean enabled)
-
getUpdateLock
public WApplication.UpdateLock getUpdateLock()
Grabs and returns the lock for manipulating widgets outside the event loop.You need to keep this lock in scope while manipulating widgets outside of the event loop. In normal cases, inside the JWt event loop, you do not need to care about it.
- See Also:
enableUpdates(boolean enabled),triggerUpdate()
-
attachThread
public void attachThread(boolean attach)
Attach an auxiliary thread to this application.In a multi-threaded environment,
getInstance()uses thread-local data to retrieve the application object that corresponds to the session currently being handled by the thread. This is set automatically by the library whenever an event is delivered to the application, or when you use theWApplication.UpdateLockto modify the application from an auxiliary thread outside the normal event loop.When you want to manipulate the widget tree inside the main event loop, but from within an auxiliary thread, then you cannot use the
WApplication.UpdateLocksince this will create an immediate dead lock. Instead, you may attach the auxiliary thread to the application, by calling this method from the auxiliary thread, and in this way you can modify the application from within that thread without needing the update lock.Calling
attachThread()withattach=false, detaches the current thread.
-
attachThread
public final void attachThread()
Attach an auxiliary thread to this application.Calls
attachThread(true)
-
doJavaScript
public void doJavaScript(java.lang.String javascript, boolean afterLoaded)Executes some JavaScript code.This method may be used to call some custom
javaScriptcode as part of an event response.This function does not wait until the JavaScript is run, but returns immediately. The JavaScript will be run after the normal event handling, unless
afterLoadedis set tofalse.In most situations, it's more robust to use
WWidget#doJavaScript()however.
-
doJavaScript
public final void doJavaScript(java.lang.String javascript)
Executes some JavaScript code.
-
addAutoJavaScript
public void addAutoJavaScript(java.lang.String javascript)
Adds JavaScript statements that should be run continuously.This is an internal method.
It is used by for example layout managers to adjust the layout whenever the DOM tree is manipulated.
-
declareJavaScriptFunction
public void declareJavaScriptFunction(java.lang.String name, java.lang.String function)Declares an application-wide JavaScript function.The function is stored in
getJavaScriptClass().The next code snippet declares and invokes function foo:
-
require
public boolean require(java.lang.String uri, java.lang.String symbol)Loads a JavaScript library.Loads a JavaScript library located at the URL
url. JWt keeps track of libraries (with the same URL) that already have been loaded, and will load a library only once. In addition, you may provide asymbolwhich if already defined will also indicate that the library was already loaded (possibly outside of JWt when inEntryPointType.WidgetSetmode).This method returns
trueonly when the library is loaded for the first time.JavaScript libraries may be loaded at any point in time. Any JavaScript code is deferred until the library is loaded, except for JavaScript that was defined to load before, passing
falseas second parameter todoJavaScript().
-
require
public final boolean require(java.lang.String uri)
Loads a JavaScript library.Returns
require(uri, "")
-
requireJQuery
public boolean requireJQuery(java.lang.String uri)
-
isCustomJQuery
public boolean isCustomJQuery()
-
setJavaScriptClass
public void setJavaScriptClass(java.lang.String javaScriptClass)
Sets the name of the application JavaScript class.This should be called right after construction of the application, and changing the JavaScript class is only supported for
EntryPointType.WidgetSetmode applications. TheclassNameshould be a valid JavaScript identifier, and should also be unique in a single page.
-
getJavaScriptClass
public java.lang.String getJavaScriptClass()
Returns the name of the application JavaScript class.This JavaScript class encapsulates all JavaScript methods specific to this application instance. The method is foreseen to allow multiple applications to run simultaneously on the same page in Wt::WidgtSet mode, without interfering.
-
processEvents
public void processEvents()
Processes UI events.You may call this method during a long operation to:
- propagate widget changes to the client.
- process UI events.
This method starts a recursive event loop, blocking the current thread, and resumes when all pending user interface events have been processed.
Because a thread is blocked, this may affect your application scalability.
-
waitForEvent
public void waitForEvent()
Blocks the thread, waiting for an UI event.This function is used by functions like
WDialog#exec()or WPopupMenu::exec(), to block the current thread waiting for a new event.This requires that at least one additional thread is available to process incoming requests, and is not scalable when working with a fixed size thread pools.
-
readConfigurationProperty
public static java.lang.String readConfigurationProperty(java.lang.String name, java.lang.String value)Reads a configuration property.Tries to read a configured value for the property
name. If no value was configured, the defaultvalueis returned.
-
getDomRoot
public WWebWidget getDomRoot()
-
destroy
public void destroy()
Destroys the application session.The application is destroyed when the session is invalidated. You should put here any logic which is needed to cleanup the application session.
The default implementation does nothing.
-
setTwoPhaseRenderingThreshold
public void setTwoPhaseRenderingThreshold(int bytes)
Changes the threshold for two-phase rendering.This changes the threshold for the
sizeof a JavaScript response (in bytes) to render invisible changes in one go. If the bandwidth for rendering the invisible changes exceed the threshold, they will be fetched in a second communication, after the visible changes have been rendered.The value is a trade-off: setting it smaller will always use two-phase rendering, increasing the total render time but reducing the latency for the visible changes. Setting it too large will increase the latency to render the visible changes, since first also all invisible changes need to be computed and received in the browser.
-
setCookie
public void setCookie(jakarta.servlet.http.Cookie cookie)
Sets a new cookie.Use cookies to transfer information across different sessions (e.g. a user name). In a subsequent session you will be able to read this cookie using
WEnvironment#getCookie(). You cannot use a cookie to store information in the current session.For more information on how to configure cookies, see the Http::Cookie class.
-
setCookie
public void setCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain, java.lang.String path, boolean secure)Deprecated.UsesetCookie()instead.Sets a new cookie.Use cookies to transfer information across different sessions (e.g. a user name). In a subsequent session you will be able to read this cookie using
WEnvironment#getCookie(). You cannot use a cookie to store information in the current session.The name must be a valid cookie name (of type 'token': no special characters or separators, see RFC2616 page 16). The value may be anything. Specify the maximum age (in seconds) after which the client must discard the cookie. To delete a cookie, use a value of '0'.
By default the cookie only applies to the application deployment path (
WEnvironment.getDeploymentPath()) in the current domain. To set a proper value for domain, see also RFC2109.
-
setCookie
public final void setCookie(java.lang.String name, java.lang.String value, int maxAge)Sets a new cookie.
-
setCookie
public final void setCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain)Sets a new cookie.
-
setCookie
public final void setCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain, java.lang.String path)Sets a new cookie.
-
removeCookie
public void removeCookie(jakarta.servlet.http.Cookie cookie)
Removes a cookie.The cookie will be removed if it has the same name, domain and path as the original cookie (RFC-6265, section 5.3.11).
- See Also:
setCookie(Cookie cookie)
-
removeCookie
public void removeCookie(java.lang.String name, java.lang.String domain, java.lang.String path)Deprecated.UseremoveCookie()instead.Removes a cookie.- See Also:
setCookie(Cookie cookie)
-
removeCookie
public final void removeCookie(java.lang.String name)
Removes a cookie.
-
removeCookie
public final void removeCookie(java.lang.String name, java.lang.String domain)Removes a cookie.
-
addMetaLink
public void addMetaLink(java.lang.String href, java.lang.String rel, java.lang.String media, java.lang.String hreflang, java.lang.String type, java.lang.String sizes, boolean disabled)Adds an HTML meta link.When a link was previously set for the same
href, its contents are replaced. When an empty string is used for the argumentsmedia,hreflang,typeorsizes, they will be ignored.- See Also:
removeMetaLink(String href)
-
removeMetaLink
public void removeMetaLink(java.lang.String href)
Removes the HTML meta link.
-
addMetaHeader
public void addMetaHeader(java.lang.String name, java.lang.CharSequence content, java.lang.String lang)Adds a "name" HTML meta header.
-
addMetaHeader
public final void addMetaHeader(java.lang.String name, java.lang.CharSequence content)Adds a "name" HTML meta header.
-
addMetaHeader
public void addMetaHeader(MetaHeaderType type, java.lang.String name, java.lang.CharSequence content, java.lang.String lang)
Adds an HTML meta header.This method sets either a "name" meta headers, which configures a document property, or a "http-equiv" meta headers, which defines a HTTP headers (but these latter headers are being deprecated).
A meta header can however only be added in the following situations:
- when a plain HTML session is used (including when the user agent is a bot), you can add meta headers at any time.
- or, when progressive bootstrap is used, you can set meta headers for any type of session, from within the application constructor (which corresponds to the initial request).
- but never for a
EntryPointType.WidgetSetmode application since then the application is hosted within a foreign HTML page.
These situations coincide with
WEnvironment.hasAjax()returningfalse(seegetEnvironment()). The reason that it other cases the HTML page has already been rendered, and will not be rerendered since all updates are done dynamically.As an alternative, you can use the <meta-headers> configuration property in the configuration file, which will be applied in all circumstances.
-
addMetaHeader
public final void addMetaHeader(MetaHeaderType type, java.lang.String name, java.lang.CharSequence content)
Adds an HTML meta header.
-
metaHeader
public WString metaHeader(MetaHeaderType type, java.lang.String name)
Returns a meta header value.
-
removeMetaHeader
public void removeMetaHeader(MetaHeaderType type, java.lang.String name)
Removes one or all meta headers.Removes the meta header with given type and name (if it is present). If name is empty, all meta headers of the given type are removed.
-
removeMetaHeader
public final void removeMetaHeader(MetaHeaderType type)
Removes one or all meta headers.
-
setLoadingIndicator
public void setLoadingIndicator(WLoadingIndicator indicator)
Sets the loading indicator.The loading indicator is shown to indicate that a response from the server is pending or JavaScript is being evaluated.
The default loading indicator is a
WDefaultLoadingIndicator.
-
getLoadingIndicator
public WLoadingIndicator getLoadingIndicator()
Returns the loading indicator.
-
quit
public void quit()
Quits the application.This quits the application with a default restart message resolved as
WString#tr()("Wt.QuittedMessage").- See Also:
quit(CharSequence restartMessage)
-
quit
public void quit(java.lang.CharSequence restartMessage)
Quits the application.The method returns immediately, but has as effect that the application will be terminated after the current event is completed.
The current widget tree (including any modifications still pending and applied during the current event handling) will still be rendered, after which the application is terminated.
If the restart message is not empty, then the user will be offered to restart the application (using the provided message) when further interacting with the application.
- See Also:
redirect(String url)
-
hasQuit
public boolean hasQuit()
Returns whether the application has quit.- See Also:
quit()
-
getMaximumRequestSize
public long getMaximumRequestSize()
Returns the current maximum size of a request to the application.The returned value is the maximum request size in bytes.
- See Also:
requestTooLarge()
-
requestTooLarge
public Signal1<java.lang.Long> requestTooLarge()
Signal which indicates that too a large request was received.The integer parameter is the request size that was received in bytes.
-
globalKeyWentDown
public EventSignal1<WKeyEvent> globalKeyWentDown()
Event signal emitted when a keyboard key is pushed down.The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.
- See Also:
WInteractWidget.keyWentDown()
-
globalKeyPressed
public EventSignal1<WKeyEvent> globalKeyPressed()
Event signal emitted when a "character" was entered.The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.
- See Also:
WInteractWidget.keyPressed()
-
globalKeyWentUp
public EventSignal1<WKeyEvent> globalKeyWentUp()
Event signal emitted when a keyboard key is released.The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.
- See Also:
WInteractWidget.keyWentUp()
-
globalEnterPressed
public EventSignal globalEnterPressed()
Event signal emitted when enter was pressed.The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.
- See Also:
WInteractWidget.enterPressed()
-
globalEscapePressed
public EventSignal globalEscapePressed()
Event signal emitted when escape was pressed.The application receives key events when no widget currently has focus. Otherwise, key events are handled by the widget in focus, and its ancestors.
- See Also:
WInteractWidget.escapePressed()
-
setFocus
public void setFocus(java.lang.String id, int selectionStart, int selectionEnd)
-
loadJavaScript
public void loadJavaScript(java.lang.String jsFile, WJavaScriptPreamble preamble)Loads an internal JavaScript file.This is an internal function and should not be called directly.
-
setConfirmCloseMessage
public void setConfirmCloseMessage(java.lang.CharSequence message)
Sets the message for the user to confirm closing of the application window/tab.If the message is empty, then the user may navigate away from the page without confirmation.
Otherwise the user will be prompted with a browser-specific dialog asking him to confirm leaving the page. This
messageis added to the page.- See Also:
unload()
-
pathMatches
public static boolean pathMatches(java.lang.String path, java.lang.String query)Utility function to check if one path falls under another path.This returns whether the
querypath matches the givenpath, meaning that it is equal to that path or it specifies a more specific sub path of that path.
-
encodeUntrustedUrl
public java.lang.String encodeUntrustedUrl(java.lang.String url)
Encodes an untrusted URL to prevent referer leaks.This encodes an URL so that in case the session ID is present in the current URL, this session ID does not leak to the refenced URL.
Wt will safely handle URLs in the API (in
WImageandWAnchor) but you may want to use this function to encode URLs which you use inWTemplatetexts.
-
addGlobalWidget
public void addGlobalWidget(WWidget w)
-
removeGlobalWidget
public void removeGlobalWidget(WWidget w)
-
suspend
public void suspend(java.time.Duration duration)
Suspend the application.Keep this application alive for a certain amount of time, while allowing the user to navigate away from the page. This can be useful when using 3rd party login or payment providers. You can later return to the application with a url that includes the session ID as query parameter (see
url()).
-
unsuspended
public Signal unsuspended()
Signalthat is emitted when the application is no longer suspended.This can be used to apply changes which were difficult to do as a result of the application not being rendered. Eg. JWt uses this to trigger a login as a result of single sign-on.
-
getServerSideFontMetrics
public eu.webtoolkit.jwt.ServerSideFontMetrics getServerSideFontMetrics()
Returns the font metrics for server-side rendering.In case we require the fallback to render things server-side, this will require the construction of font metrics. The application will construct this object only once, as an optimization.
In case the object did not yet exist, a new instance is created.
-
notify
protected void notify(WEvent e) throws java.io.IOException
Notifies an event to the application.This method is called by the event loop for propagating an event to the application. It provides a single point of entry for events to the application, besides the application constructor.
You may want to reimplement this method for two reasons:
- for having a single point for exception handling: while you may want to catch recoverable exceptions in a more appropriate place, general (usually fatal) exceptions may be caught here. You will probably want to catch the same exceptions in the application constructor in the same way.
- you want to manage resource usage during requests. For example, at the end of request handling, you want to return a database session back to the pool. Since notify() is also used for rendering right after the application is created, this will also clean up resources after application construction.
In either case, you will need to call the base class implementation of notify(), as otherwise no events will be delivered to your application.
The following shows a generic template for reimplementhing this method for both managing request resources and generic exception handling.
void notify(WEvent event) { // Grab resources for during request handling try { super.notify(event); } catch (MyException exception) { // handle this exception in a central place } // Free resources used during request handling }Note that any uncaught exception throw during event handling terminates the session.
- Throws:
java.io.IOException
-
isExposed
protected boolean isExposed(WWidget w)
Returns whether a widget is exposed in the interface.The default implementation simply returns
true, unless a modal dialog is active, in which case it returnstrueonly for widgets that are inside the dialog.You may want to reimplement this method if you wish to disallow events from certain widgets even when they are inserted in the widget hierachy.
-
enableAjax
protected void enableAjax()
Progresses to an Ajax-enabled user interface.This method is called when the progressive bootstrap method is used, and support for AJAX has been detected. The default behavior will propagate the
WWidget.enableAjax()method through the widget hierarchy.You may want to reimplement this method if you want to make changes to the user-interface when AJAX is enabled. You should always call the base implementation.
- See Also:
WWidget.enableAjax()
-
unload
protected void unload()
Handles a browser unload event.The browser unloads the application when the user navigates away or when he closes the window or tab.
When
reload-is-new-sessionis set totrue, then the default implementation of this method terminates this session by callingquit(), otherwise the session is scheduled to expire within seconds (since it may be a refresh).You may want to reimplement this if you want to keep the application running until it times out.
Note: There is no guarantee that closing the browser tab sends the unload event. This is because it is at the web browser's discretion whether it still sends requests for a closed tab. It's also possible that there was no connection upon closing the tab. Sessions that don't receive the unload event will eventually time out according to the
session-timeoutset inwt_config.xml(this defaults to 10 minutes).
-
idleTimeout
protected void idleTimeout()
Idle timeout handler.If idle timeout is set in the configuration (Configuration#setIdleTimeout(int)), this method is called when the user seems idle for the number of seconds set as the idle timeout.
This feature can be useful in security sensitive applications to prevent unauthorized users from taking over the session of a user that has moved away from or left behind the device from which they are accessing the JWt application.
The default implementation logs that a timeout has occurred, and calls
quit().This method can be overridden to specify different timeout behaviour, e.g. to show a dialog that a user's session has expired, or that the session is about to expire.
Note: The events currently counted as user activity are:
- mousedown
- mouseup
- wheel
- keydown
- keyup
- touchstart
- touchend
- pointerdown
- pointerup
-
handleJavaScriptError
protected void handleJavaScriptError(java.lang.String errorText)
handleJavaScriptError print javaScript errors to log file. You may want to overwrite it to render error page for example.- Parameters:
errorText- the error will usually be in json format.
-
findAddedCookies
public java.lang.String findAddedCookies(java.lang.String name)
-
-