Class HtmlPage
- Direct Known Subclasses:
HtmlTemplatePage
HtmlPage provides the foundation for building dynamic web pages with real-time client-server communication. It manages the page lifecycle, element hierarchy, event dispatching, and DOM synchronization via WebSocket, SSE, or AJAX.
Subclasses implement createHead(Head) and createBody(Body) to build
the page content. The page maintains a persistent connection to the browser, allowing
server-side code to update the DOM in real time.
- Since:
- 2007
- Version:
- 1.0
- Author:
- Marvin P. Warble Jr.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal voidaddAttribute(String key, String value) Adds an attribute to the HTML element of this page.voidaddAttributeUpdate(Element element) voidaddCommand(Command command) final OorianCookieaddCookie(OorianCookie cookie) final OorianCookiefinal HtmlPageaddElement(Element child) Adds a child element to the page.voidaddElementAddition(Element element) voidaddElementSubtraction(Element element) voidaddElementUpdate(Element element) final voidBlocks the page from unloading by showing a confirmation dialog.final voidclearWatch(String watchId) Stops watching the geographic position.final voidCloses the WebSocket connection for this page.final voidcloseWindow(String windowName) Closes the browser window with the specified name.final StringcreateAppUrl(String url) Creates an application-relative URL.protected abstract voidcreateBody(Body body) Creates the body section of this page.protected final voidCreates the HTML structure of this page including head, body, scripts, and styles.final StringcreateFullUrl(String url) Creates a fully-qualified URL from a relative URL.protected abstract voidcreateHead(Head head) Creates the head section of this page.static StringCreates a URL for navigating to a page class with optional parameters.voiddispatchEvent(ExtServerEvent event) Dispatches an extended server event to registered listeners.voiddispatchEvent(PageEvent event) Dispatches a page event to registered listeners.voiddispatchEvent(ServerEvent event) Dispatches a server event to registered listeners.final voidExecutes a JavaScript statement on the client.final voidExecutes a JavaScript function on the client with the specified parameters.final BodygetBody()Returns the body element of this page.final CommunicationModeGets the asynchronous communication mode for this page.final OorianCookieReturns a cookie by name.final OorianCookieReturns a cookie by name, or a cookie with the default value if not found.Returns the cookies collection for this page's request.final voidRequests the current geographic position.final voidgetCurrentPosition(GeolocationOptions options) Requests the current geographic position with options.longReturns the time when the page became disconnected.final ElementgetElementById(String id) Finds and returns an element on this page by its ID.final ElementsgetElementsByTagName(String tagName, boolean recursive) Returns all elements on this page that match the specified HTML tag name.getHash()Returns the current URL hash fragment, without the leading#character.final HeadgetHead()Returns the head element of this page.Returns the inner HTML content of this page as a string.final StringReturns the client's IP address.longReturns the time of the last activity on this page.final intReturns the document height in logical (CSS) pixels.final intReturns the document width in logical (CSS) pixels.static HtmlPagegetPage()final StringReturns the unique identifier for this page instance.Returns the current lifecycle state of this page.final intReturns the document height in physical (device) pixels.final intReturns the document width in physical (device) pixels.final intReturns the screen height in physical (device) pixels.final intReturns the screen width in physical (device) pixels.final intReturns the browser window height in physical (device) pixels.final intReturns the browser window width in physical (device) pixels.final floatReturns the device pixel ratio.longGets the polling interval for AJAX_ONLY mode.final StringReturns the full URL of the previous page in the browser history.Returns the HTTP referrer header.Returns the referring page path.Returns the request host.final intReturns the screen height in logical (CSS) pixels.final OrientationReturns the current screen orientation.final SizeReturns the screen size in logical (CSS) pixels.final intReturns the screen width in logical (CSS) pixels.final OorianSessionReturns the current Oorian session.Returns the temporary file directory for uploads.final StringReturns the client's user agent string.final intReturns the client's UTC timezone offset in minutes.final intReturns the browser window (viewport) height in logical (CSS) pixels.final OrientationReturns the current window orientation.final SizeReturns the browser window size in logical (CSS) pixels.final intReturns the browser window (viewport) width in logical (CSS) pixels.voidhandleAjaxRequest(OorianHttpRequest request, OorianHttpResponse response) Handles an incoming AJAX request from the client.voidCalled when the SSE connection for this page is closed.voidhandleSseOpen(SseConnection sseConnection) Called when an SSE connection is opened for this page.voidHandles a WebSocket close event for this page.voidhandleWebsocketError(Throwable error) Handles a WebSocket error for this page.voidhandleWebsocketMessage(OorianHttpSession session, String msg) Handles an incoming WebSocket message.voidhandleWebsocketOpen(WebsocketConnection websocket) Called when a WebSocket connection is opened for this page.voidhandleWebSocketRequest(Parameters params) Handles an incoming WebSocket request from the client.final voidhistoryPushState(String title, String url) Pushes a new state onto the browser history stack.final voidhistoryReplaceState(String title, String url) Replaces the current state in the browser history.protected final booleanInitializes this page when first requested by the client.protected booleanInitializes this page for the current request.final booleanChecks whether CSRF protection is enabled for this page.booleanChecks if the window width indicates a desktop device.booleanisDisconnectedTimeout(long timeoutMillis) Checks if the page has been disconnected longer than the specified timeout.final booleanChecks if the device has a high-DPI (Retina) display.final booleanChecks if the screen is in landscape orientation.final booleanisLoaded()Checks if this page has been loaded in the browser.booleanisMobile()Checks if the window width indicates a mobile device.final booleanChecks if the screen is in portrait orientation.final booleanReturns whether the page response has been written to the client.booleanisTablet()Checks if the window width indicates a tablet device.booleanChecks if this page has been unloaded from the browser.final voidPreloads a single image on the client for improved performance.final voidloadImages(List<String> imageUrls) Preloads a list of images on the client for improved performance.final voidloadScript(String filename) Loads a JavaScript file on the client.final voidloadScript(String filename, boolean includeTimestamp) Loads a JavaScript file on the client with optional cache-busting.final voidmakeSameHeight(Element element, Element match) Makes a single element the same height as the match element on page load.final voidmakeSameHeight(Collection<Element> elements, Element match) Makes all specified elements the same height as the match element on page load.final voidmakeSameHeightMax(Collection<Element> elements) Makes all specified elements the same height, matching the tallest element on page load.final voidmakeSameHeightMin(Collection<Element> elements) Makes all specified elements the same height, matching the shortest element on page load.final voidmakeSameSize(Collection<Element> elements, Element match) Makes all specified elements the same size as the match element on page load.final voidmakeSameSizeMax(Collection<Element> elements) Makes all specified elements the same size, matching the largest element on page load.final voidmakeSameSizeMin(Collection<Element> elements) Makes all specified elements the same size, matching the smallest element on page load.final voidmakeSameWidth(Collection<Element> elements, Element match) Makes all specified elements the same width as the match element on page load.final voidmakeSameWidthMax(Collection<Element> elements) Makes all specified elements the same width, matching the widest element on page load.final voidmakeSameWidthMin(Collection<Element> elements) Makes all specified elements the same width, matching the narrowest element on page load.final voidNavigates back one page in the browser history.final voidnavigateBack(int pages) Navigates back the specified number of pages in the browser history.final voidnavigateBackAfterDelay(long msecs) Navigates back in the browser history after a delay.final voidNavigates forward one page in the browser history.final voidnavigateForward(int pages) Navigates forward the specified number of pages in the browser history.final voidnavigateTo(String url) Navigates to the specified URL.final voidnavigateToAfterDelay(String url, long msecs) Navigates to the specified URL after a delay.final voidNavigates to the previous page in the browser history.final voidNavigates to the referring page.protected voidonCallback(String callbackId) Called when a client-side callback is triggered.protected voidonClientDataEvent(Parameters params) Called when a client data event is received from the browser.protected voidCalled when the HTML document dimensions change.protected booleanonException(Exception exception) Called when an exception occurs during page creation or processing.protected voidonJsReturn(String callbackId, String retval) Called when a JavaScript function returns a value to the server.protected voidonJsReturn(String elementId, String callbackId, String retval) Called when a JavaScript function returns a value to the server for a specific element.protected voidonLoaded()Called when the page has finished loading in the browser.protected voidCalled when the page is refreshed viarefresh().protected voidonRequest(OorianHttpRequest request, OorianHttpResponse response) Subclasses should override this method if they need to do any pre-processing before a request is processed by the framework and passed on to application level classes.protected voidCalled after a response has been successfully sent to the client.protected voidCalled when the client's screen size changes.protected voidCalled when the user's session has expired during a WebSocket message.protected voidCalled when the SSE connection for this page is closed.protected voidCalled when an SSE connection is opened for this page.protected voidCalled when the page is unloaded from the browser.protected voidonUserEvent(Parameters params) Called when a custom user event is received from the client.protected voidonWebsocketClose(ConnectionCloseInfo reason) Called when the WebSocket connection for this page is closed.protected voidonWebsocketError(Throwable error) Called when a WebSocket error occurs for this page.protected voidonWebsocketMessage(String msg) Called when a WebSocket message is received from the client.protected voidCalled when a WebSocket connection is opened for this page.protected voidCalled when the browser window (viewport) is resized.final voidopenInNewWindow(String url) Opens a URL in a new browser window.final voidopenInNewWindow(String url, String target) Opens a URL in a new browser window with the specified target.final voidopenInNewWindow(String url, String name, String specs) Opens a URL in a new browser window with the specified name and window features.final voidprint()Opens the browser's print dialog.final voidPrints the content of the specified page.final voidPrints the content from the specified URL.final voidrecreate()Recreates the page body by removing all elements and callingcreateBody(Body)again.final voidrefresh()Refreshes the page and all its child elements.final voidRefreshes all child elements except the element that initiated the refresh.final voidregisterAttributeUpdate(Element element) Registers an attribute update on an element to be synchronized with the client.final voidregisterElementAddition(Element element) Registers an element addition to be synchronized with the client.final voidregisterElementSubtraction(Element element) Registers an element removal to be synchronized with the client.final voidregisterElementUpdate(Element element) Registers an element update to be synchronized with the client.voidregisterListener(ExtServerEventListener listener, Class<? extends ExtServerEvent>... eventTypes) Registers a listener for one or more extended server event types.voidregisterListener(PageEventListener listener, Class<? extends PageEvent>... eventTypes) Registers a listener for one or more page event types.voidregisterListener(ServerEventListener listener, Class<? extends ServerEvent>... eventTypes) Registers a listener for one or more server event types.final voidreload()Reloads the current page.final voidreloadAfterDelay(long msecs) Reloads the page after a delay.final voidRemoves all child elements from this page.final voidremoveElement(Element child) Removes a child element from this page.final voidremoveElement(String id) Removes a child element from this page by its ID.static StringresolveUrl(String url) Resolves a URL by prepending the application context path if necessary.voidsendAjaxResponse(OorianHttpResponse servletResponse) final voidsendCommand(Command command) Sends a command to the client.voidSends pending updates to the client via the SSE connection.voidSends pending updates to the client using the configured communication mode.voidvoidSets the body element for this page.final voidsetClientInterval(String script, long intervalMs) Executes JavaScript code repeatedly at a fixed interval on the client.final voidsetClientTimeout(String script, long delayMs) Executes JavaScript code after a delay on the client.final HtmlPagesetCommunicationMode(CommunicationMode communicationMode) Sets the asynchronous communication mode for this page.final voidsetCsrfProtectionEnabled(boolean enableCsrfProtection) Overrides the application-level CSRF protection setting for this specific page.final voidsetDescription(String descr) Sets the meta description for search engine optimization.final HtmlPagesetDir(TextDirection direction) Sets the text direction for the document.final HtmlPageSets the text direction for the document using a string value.final voidsetEnableCsrfProtection(boolean enableCsrfProtection) Deprecated.voidSets the head element for this page.final voidsetKeywords(String keywords) Sets the meta keywords for search engine optimization.final HtmlPageSets the document language for accessibility and SEO.final voidsetOorianScriptPath(String path) Sets the path to the Oorian JavaScript file for this page, overriding the application-wide default set via.invalid reference
Application#setOorianScript(String)setPollInterval(long pollInterval) Sets the polling interval for AJAX_ONLY mode.final voidsetReloadOnBack(boolean reloadOnBack) Sets whether the page should reload when navigating back.final voidSets the meta robots directive for search engine crawlers.final voidsetTempFileDir(String tempFileDir) Sets the directory for temporary file uploads.final voidSets the page title displayed in the browser tab.protected final voidGenerates the complete HTML document string including the DOCTYPE declaration.final voidUnblocks the page from unloading.final booleanuserAgentContains(String keyword) Checks if the user agent contains a specified keyword.final StringStarts watching the geographic position.final StringwatchPosition(GeolocationOptions options) Starts watching the geographic position with options.Methods inherited from class com.oorian.HttpFile
addResponseHeader, create, getCacheControl, getDocumentUrl, getFullUrl, getHost, getHttpRequest, getOriginalParameters, getParameter, getParameterAsFloat, getParameterAsInt, getParameterAsLong, getParameterAsShort, getParameters, getParametersAFloat, getParametersAsInt, getParametersAsLong, getParametersAsShort, getParameterValues, getPath, getServletPath, getSessionId, getUrl, getUrlParameters, getWebResponse, hasParameter, hasUrlParams, isWritten, onCreated, onWriteComplete, setCacheControl, setCharacterEncoding, setContentType, setResponseHeader, setUrlParameters, toString, toString, write
-
Constructor Details
-
HtmlPage
public HtmlPage()Creates a new HtmlPage with default settings.Initializes the head, body, event dispatcher, request handler, and sets the communication mode to the application default.
-
-
Method Details
-
resolveUrl
Resolves a URL by prepending the application context path if necessary.This method handles URLs that start with "/" by prepending the servlet context path. URLs that are already absolute (http://, https://) or protocol-relative (//) are returned unchanged.
This method should be used when constructing URLs for href, src, action attributes to ensure they work correctly regardless of the application's deployment context path.
- Parameters:
url- The URL to resolve.- Returns:
- The resolved URL with context path prepended if applicable.
-
createUrl
Creates a URL for navigating to a page class with optional parameters.This method resolves the URL pattern defined in the page's
@Pageannotation and substitutes any path parameters with the provided arguments.The returned URL includes the application context path, so it can be used directly in href, src, or action attributes.
- Parameters:
pageClass- The page class annotated with@Page.args- The arguments to substitute into URL path parameters, in order.- Returns:
- The constructed URL string with context path included.
- Throws:
PageUrlException- If the number of arguments doesn't match the number of URL parameters.
-
handleAjaxRequest
Handles an incoming AJAX request from the client.Processes the request parameters, dispatches events to appropriate handlers, and sends the response back to the client.
- Parameters:
request- The HTTP servlet request containing event data.response- The HTTP servlet response to send updates back to the client.
-
handleWebSocketRequest
Handles an incoming WebSocket request from the client.Processes the request parameters from a WebSocket message and sends any updates back through the WebSocket connection.
- Parameters:
params- The parameters extracted from the WebSocket message.
-
handleWebsocketOpen
Called when a WebSocket connection is opened for this page.Stores the WebSocket reference and invokes the
onWebsocketOpen()callback to allow subclasses to perform initialization when the connection is established.- Parameters:
websocket- The WebSocket connection instance.
-
handleWebsocketMessage
Handles an incoming WebSocket message.Parses the JSON message, extracts parameters, and dispatches the request to the appropriate handlers. Handles session validation and error cases.
- Parameters:
session- The HTTP session associated with the WebSocket connection.msg- The raw JSON message string from the client.
-
handleWebsocketError
Handles a WebSocket error for this page.Delegates to
onWebsocketError(Throwable)for custom error handling.- Parameters:
error- The error that occurred.
-
handleWebsocketClose
Handles a WebSocket close event for this page.Delegates to
onWebsocketClose(ConnectionCloseInfo)for custom close handling.- Parameters:
reason- The reason the WebSocket was closed.
-
handleSseOpen
Called when an SSE connection is opened for this page.- Parameters:
sseConnection- The SSE connection.
-
handleSseClose
public void handleSseClose()Called when the SSE connection for this page is closed. -
setHead
Sets the head element for this page.- Parameters:
head- The head element containing metadata, scripts, and stylesheets.
-
setBody
Sets the body element for this page.- Parameters:
body- The body element containing the page content.
-
setTitle
Sets the page title displayed in the browser tab.- Parameters:
title- The page title.
-
setKeywords
Sets the meta keywords for search engine optimization.- Parameters:
keywords- A comma-separated list of keywords.
-
setDescription
Sets the meta description for search engine optimization.- Parameters:
descr- The page description.
-
setRobots
Sets the meta robots directive for search engine crawlers.- Parameters:
robots- The robots directive (e.g., "index, follow" or "noindex, nofollow").
-
setOorianScriptPath
Sets the path to the Oorian JavaScript file for this page, overriding the application-wide default set via.invalid reference
Application#setOorianScript(String)The path should be the full path including the filename, relative to the application context root (e.g.,
"/js/oorian-core-2.0.500.js"or"/oorian.min.js").- Parameters:
path- The full path to the Oorian JavaScript file.
-
setTempFileDir
Sets the directory for temporary file uploads.- Parameters:
tempFileDir- The path to the temporary file directory.
-
setCsrfProtectionEnabled
public final void setCsrfProtectionEnabled(boolean enableCsrfProtection) Overrides the application-level CSRF protection setting for this specific page.By default, pages inherit the CSRF protection setting from the application (see
). This method allows individual pages to override that setting.invalid reference
Application#setCsrfProtectionEnabled(boolean)Use this sparingly - it's generally better to keep CSRF protection enabled application-wide and only disable it for specific pages that require it (such as public API endpoints or webhook receivers).
- Parameters:
enableCsrfProtection-trueto enable CSRF protection for this page,falseto disable it.
-
setEnableCsrfProtection
Deprecated.UsesetCsrfProtectionEnabled(boolean)instead.- Parameters:
enableCsrfProtection-trueto enable,falseto disable.
-
isCsrfProtectionEnabled
public final boolean isCsrfProtectionEnabled()Checks whether CSRF protection is enabled for this page.Returns the page-level override if set, otherwise returns the application-level setting.
- Returns:
trueif CSRF protection is enabled,falseotherwise.
-
setReloadOnBack
public final void setReloadOnBack(boolean reloadOnBack) Sets whether the page should reload when navigating back.- Parameters:
reloadOnBack-trueto reload on back navigation,falseotherwise.
-
setCommunicationMode
Sets the asynchronous communication mode for this page.- Parameters:
communicationMode- The communication mode to use.- Returns:
- This HtmlPage instance for method chaining.
-
getCommunicationMode
Gets the asynchronous communication mode for this page.- Returns:
- The current communication mode.
-
setPollInterval
Sets the polling interval for AJAX_ONLY mode.When the communication mode is AJAX_ONLY, this interval determines how often the client will poll the server for pending updates.
- Parameters:
pollInterval- The polling interval in milliseconds (-1 = app default, 0 = disabled).- Returns:
- This HtmlPage instance for method chaining.
- See Also:
-
getPollInterval
public long getPollInterval()Gets the polling interval for AJAX_ONLY mode.- Returns:
- The polling interval in milliseconds.
- See Also:
-
addElement
Adds a child element to the page.- Parameters:
child- The element to add.- Returns:
- This page for method chaining.
-
removeElement
Removes a child element from this page.- Parameters:
child- The element to remove.
-
removeElement
Removes a child element from this page by its ID.- Parameters:
id- The ID of the element to remove.
-
removeAllElements
public final void removeAllElements()Removes all child elements from this page. -
addAttribute
Adds an attribute to the HTML element of this page.- Parameters:
key- The attribute name.value- The attribute value.
-
setLang
Sets the document language for accessibility and SEO.The lang attribute is required for WCAG compliance. It helps screen readers use the correct pronunciation rules and enables proper font selection for different scripts.
Common language codes:
- "en" - English
- "en-US" - American English
- "en-GB" - British English
- "es" - Spanish
- "fr" - French
- "de" - German
- "ja" - Japanese
- "zh" - Chinese
- "ar" - Arabic
- Parameters:
languageCode- BCP 47 language code (e.g., "en", "en-US", "es", "fr").- Returns:
- This page for method chaining.
-
setDir
Sets the text direction for the document.Use this for languages that are written right-to-left, such as Arabic, Hebrew, Persian, and Urdu. This affects the default alignment and flow direction of text throughout the document.
- Parameters:
direction- LTR for left-to-right, RTL for right-to-left.- Returns:
- This page for method chaining.
-
setDir
Sets the text direction for the document using a string value.- Parameters:
direction- "ltr" for left-to-right, "rtl" for right-to-left.- Returns:
- This page for method chaining.
-
getPageId
Returns the unique identifier for this page instance.- Returns:
- The page ID.
-
getPreviousFullUrl
Returns the full URL of the previous page in the browser history.- Returns:
- The previous page URL, or
nullif not available.
-
getCookies
Returns the cookies collection for this page's request.- Returns:
- The cookies collection.
-
getCookie
Returns a cookie by name.- Parameters:
name- The cookie name.- Returns:
- The cookie, or
nullif not found.
-
getCookie
Returns a cookie by name, or a cookie with the default value if not found.- Parameters:
name- The cookie name.defaultValue- The default value if the cookie is not found.- Returns:
- The cookie, or a new cookie with the default value.
-
getTempFileDir
Returns the temporary file directory for uploads.- Returns:
- The temporary file directory path.
-
getRequestHost
Returns the request host.- Returns:
- The request host name.
-
getReferrer
Returns the HTTP referrer header.- Returns:
- The referrer URL.
-
getReferringPage
Returns the referring page path.- Returns:
- The referring page path.
-
getHash
Returns the current URL hash fragment, without the leading#character.The hash is set when the browser notifies the server of a hash change via the
hashchangeevent. Returnsnullif no hash has been received.- Returns:
- the hash fragment (e.g., "section-name"), or null if none
-
getLogicalDocumentWidth
public final int getLogicalDocumentWidth()Returns the document width in logical (CSS) pixels.- Returns:
- The document width in logical pixels.
-
getLogicalDocumentHeight
public final int getLogicalDocumentHeight()Returns the document height in logical (CSS) pixels.- Returns:
- The document height in logical pixels.
-
getPhysicalDocumentWidth
public final int getPhysicalDocumentWidth()Returns the document width in physical (device) pixels.- Returns:
- The document width in physical pixels.
-
getPhysicalDocumentHeight
public final int getPhysicalDocumentHeight()Returns the document height in physical (device) pixels.- Returns:
- The document height in physical pixels.
-
getElementById
Finds and returns an element on this page by its ID.- Parameters:
id- The ID of the element to find.- Returns:
- The element with the specified ID, or
nullif not found.
-
getElementsByTagName
Returns all elements on this page that match the specified HTML tag name.- Parameters:
tagName- The HTML tag name to search for (e.g., "div", "span").recursive-trueto search all descendants,falsefor direct children only.- Returns:
- A collection of matching elements.
-
getHead
Returns the head element of this page.- Returns:
- The Head element containing metadata, scripts, and stylesheets.
-
getBody
Returns the body element of this page.- Returns:
- The Body element containing the page content.
-
getSession
Returns the current Oorian session.- Returns:
- The OorianSession for the current request.
-
getInnerHtml
Returns the inner HTML content of this page as a string.- Returns:
- The inner HTML of the page.
-
isLoaded
public final boolean isLoaded()Checks if this page has been loaded in the browser.- Returns:
trueif the page is loaded,falseotherwise.
-
isUnloaded
public boolean isUnloaded()Checks if this page has been unloaded from the browser.- Returns:
trueif the page is unloaded,falseotherwise.
-
dispatchEvent
Dispatches a server event to registered listeners.- Parameters:
event- The server event to dispatch.
-
dispatchEvent
Dispatches an extended server event to registered listeners.- Parameters:
event- The extended server event to dispatch.
-
dispatchEvent
Dispatches a page event to registered listeners.- Parameters:
event- The page event to dispatch.
-
registerListener
public void registerListener(ServerEventListener listener, Class<? extends ServerEvent>... eventTypes) Registers a listener for one or more server event types.- Parameters:
listener- The listener to register.eventTypes- The event types to listen for.
-
registerListener
public void registerListener(ExtServerEventListener listener, Class<? extends ExtServerEvent>... eventTypes) Registers a listener for one or more extended server event types.- Parameters:
listener- The listener to register.eventTypes- The event types to listen for.
-
registerListener
Registers a listener for one or more page event types.- Parameters:
listener- The listener to register.eventTypes- The event types to listen for.
-
closeWebSocket
public final void closeWebSocket()Closes the WebSocket connection for this page. -
loadScript
Loads a JavaScript file on the client.The script is cached by the browser. Duplicate load requests for the same file are ignored.
- Parameters:
filename- The path to the JavaScript file.
-
loadScript
Loads a JavaScript file on the client with optional cache-busting.- Parameters:
filename- The path to the JavaScript file.includeTimestamp-trueto append a timestamp for cache-busting.
-
sendCommand
Sends a command to the client.If the page is loaded, the command is added to the thread updates queue. Otherwise, it is added to the initial updates queue.
- Parameters:
command- The command to send.
-
registerElementAddition
Registers an element addition to be synchronized with the client.- Parameters:
element- The element that was added.
-
registerElementSubtraction
Registers an element removal to be synchronized with the client.- Parameters:
element- The element that was removed.
-
registerElementUpdate
Registers an element update to be synchronized with the client.- Parameters:
element- The element that was updated.
-
registerAttributeUpdate
Registers an attribute update on an element to be synchronized with the client.- Parameters:
element- The element whose attributes were updated.
-
executeJs
Executes a JavaScript statement on the client.- Parameters:
script- The JavaScript code to execute.
-
executeJs
Executes a JavaScript function on the client with the specified parameters.- Parameters:
functionName- The JavaScript function name.parameters- The parameters to pass to the function.
-
blockPageUnload
public final void blockPageUnload()Blocks the page from unloading by showing a confirmation dialog. -
unblockPageUnload
public final void unblockPageUnload()Unblocks the page from unloading. -
reloadAfterDelay
public final void reloadAfterDelay(long msecs) Reloads the page after a delay.- Parameters:
msecs- The delay in milliseconds before reloading.
-
historyPushState
Pushes a new state onto the browser history stack.- Parameters:
title- The title for the new history entry.url- The URL for the new history entry.
-
historyReplaceState
Replaces the current state in the browser history.- Parameters:
title- The title for the history entry.url- The URL for the history entry.
-
openInNewWindow
Opens a URL in a new browser window.- Parameters:
url- The URL to open.
-
openInNewWindow
Opens a URL in a new browser window with the specified target.- Parameters:
url- The URL to open.target- The target window name.
-
openInNewWindow
Opens a URL in a new browser window with the specified name and window features.- Parameters:
url- The URL to open.name- The window name.specs- The window features specification.
-
closeWindow
Closes the browser window with the specified name.- Parameters:
windowName- The name of the window to close.
-
print
public final void print()Opens the browser's print dialog. -
print
Prints the content from the specified URL.- Parameters:
url- The URL of the content to print.
-
print
Prints the content of the specified page.- Parameters:
page- The page to print.
-
getScreenWidth
public final int getScreenWidth()Returns the screen width in logical (CSS) pixels.- Returns:
- The screen width in logical pixels.
-
getScreenHeight
public final int getScreenHeight()Returns the screen height in logical (CSS) pixels.- Returns:
- The screen height in logical pixels.
-
getScreenSize
Returns the screen size in logical (CSS) pixels.- Returns:
- The Size object containing screen width and height.
-
getPhysicalScreenWidth
public final int getPhysicalScreenWidth()Returns the screen width in physical (device) pixels.- Returns:
- The screen width in physical pixels.
-
getPhysicalScreenHeight
public final int getPhysicalScreenHeight()Returns the screen height in physical (device) pixels.- Returns:
- The screen height in physical pixels.
-
getWindowWidth
public final int getWindowWidth()Returns the browser window (viewport) width in logical (CSS) pixels.- Returns:
- The window width in logical pixels.
-
getWindowHeight
public final int getWindowHeight()Returns the browser window (viewport) height in logical (CSS) pixels.- Returns:
- The window height in logical pixels.
-
getWindowSize
Returns the browser window size in logical (CSS) pixels.- Returns:
- The Size object containing window width and height.
-
getPhysicalWindowWidth
public final int getPhysicalWindowWidth()Returns the browser window width in physical (device) pixels.- Returns:
- The window width in physical pixels.
-
getPhysicalWindowHeight
public final int getPhysicalWindowHeight()Returns the browser window height in physical (device) pixels.- Returns:
- The window height in physical pixels.
-
getPixelRatio
public final float getPixelRatio()Returns the device pixel ratio.The pixel ratio indicates the relationship between physical pixels and logical (CSS) pixels. Standard displays have a ratio of 1.0, while high-DPI displays like Retina screens have ratios of 2.0 or higher.
- Returns:
- The device pixel ratio.
-
isHighDpi
public final boolean isHighDpi()Checks if the device has a high-DPI (Retina) display.- Returns:
trueif the pixel ratio is 1.5 or higher,falseotherwise.
-
getScreenOrientation
Returns the current screen orientation.- Returns:
- The screen orientation (PORTRAIT or LANDSCAPE).
-
getWindowOrientation
Returns the current window orientation.- Returns:
- The window orientation (PORTRAIT or LANDSCAPE).
-
isPortrait
public final boolean isPortrait()Checks if the screen is in portrait orientation.- Returns:
trueif the screen is taller than it is wide,falseotherwise.
-
isLandscape
public final boolean isLandscape()Checks if the screen is in landscape orientation.- Returns:
trueif the screen is wider than it is tall,falseotherwise.
-
isMobile
public boolean isMobile()Checks if the window width indicates a mobile device.Subclasses may override this method to use custom breakpoints.
- Returns:
trueif the window width is less than or equal to the mobile breakpoint.
-
isTablet
public boolean isTablet()Checks if the window width indicates a tablet device.Subclasses may override this method to use custom breakpoints.
- Returns:
trueif the window width is between mobile and tablet breakpoints.
-
isDesktop
public boolean isDesktop()Checks if the window width indicates a desktop device.Subclasses may override this method to use custom breakpoints.
- Returns:
trueif the window width is greater than the tablet breakpoint.
-
getUserAgent
Returns the client's user agent string.- Returns:
- The user agent string from the browser.
-
userAgentContains
Checks if the user agent contains a specified keyword.- Parameters:
keyword- The keyword to search for (case-insensitive).- Returns:
trueif the user agent contains the keyword,falseotherwise.
-
getUtcOffset
public final int getUtcOffset()Returns the client's UTC timezone offset in minutes.- Returns:
- The UTC offset in minutes (negative for west of UTC, positive for east).
-
getIpAddress
Returns the client's IP address.- Returns:
- The client's IP address as a string.
-
setClientTimeout
Executes JavaScript code after a delay on the client.This is equivalent to JavaScript's
setTimeout().- Parameters:
script- The JavaScript code to execute.delayMs- The delay in milliseconds before executing.
-
setClientInterval
Executes JavaScript code repeatedly at a fixed interval on the client.This is equivalent to JavaScript's
setInterval().- Parameters:
script- The JavaScript code to execute.intervalMs- The interval in milliseconds between executions.
-
getCurrentPosition
public final void getCurrentPosition()Requests the current geographic position.This is a one-time request. When the position is obtained, a
GeolocationEventis dispatched to the page body. If an error occurs, aGeolocationErrorEventis dispatched instead.To receive the events, register listeners on the body element:
getBody().registerListener(this, GeolocationEvent.class); getBody().registerListener(this, GeolocationErrorEvent.class); -
getCurrentPosition
Requests the current geographic position with options.This is a one-time request. When the position is obtained, a
GeolocationEventis dispatched to the page body. If an error occurs, aGeolocationErrorEventis dispatched instead.- Parameters:
options- Configuration options for the position request (accuracy, timeout, etc.).
-
watchPosition
Starts watching the geographic position.This sets up continuous position tracking. A
GeolocationEventis dispatched to the page body each time the position changes. The returned watch ID can be used to stop tracking viaclearWatch(String).To receive the events, register listeners on the body element:
getBody().registerListener(this, GeolocationEvent.class); getBody().registerListener(this, GeolocationErrorEvent.class);- Returns:
- A watch ID that can be used to stop tracking.
-
watchPosition
Starts watching the geographic position with options.This sets up continuous position tracking. A
GeolocationEventis dispatched to the page body each time the position changes. The returned watch ID can be used to stop tracking viaclearWatch(String).- Parameters:
options- Configuration options for position tracking (accuracy, timeout, etc.).- Returns:
- A watch ID that can be used to stop tracking.
-
clearWatch
Stops watching the geographic position.- Parameters:
watchId- The watch ID returned fromwatchPosition().
-
recreate
public final void recreate()Recreates the page body by removing all elements and callingcreateBody(Body)again. -
refresh
public final void refresh()Refreshes the page and all its child elements. -
refresh
Refreshes all child elements except the element that initiated the refresh.- Parameters:
refresher- The element that initiated the refresh, to be excluded.
-
reload
public final void reload()Reloads the current page. -
isResponseWritten
public final boolean isResponseWritten()Returns whether the page response has been written to the client.- Returns:
trueif the page has been written,falseotherwise.
-
loadImages
Preloads a list of images on the client for improved performance.- Parameters:
imageUrls- The list of image URLs to preload.
-
loadImage
Preloads a single image on the client for improved performance.- Parameters:
imageUrl- The URL of the image to preload.
-
createAppUrl
Creates an application-relative URL.Prepends the application context path to the given URL.
- Parameters:
url- The relative URL.- Returns:
- The full application URL.
-
createFullUrl
Creates a fully-qualified URL from a relative URL.- Parameters:
url- The relative or absolute URL.- Returns:
- The fully-qualified URL.
- Throws:
MalformedURLException- If the URL is malformed.
-
makeSameSize
Makes all specified elements the same size as the match element on page load.- Parameters:
elements- The elements to resize.match- The element whose size will be matched.
-
makeSameSizeMax
Makes all specified elements the same size, matching the largest element on page load.- Parameters:
elements- The elements to resize to match the largest.
-
makeSameSizeMin
Makes all specified elements the same size, matching the smallest element on page load.- Parameters:
elements- The elements to resize to match the smallest.
-
makeSameHeight
Makes all specified elements the same height as the match element on page load.- Parameters:
elements- The elements to resize.match- The element whose height will be matched.
-
makeSameHeight
Makes a single element the same height as the match element on page load.- Parameters:
element- The element to resize.match- The element whose height will be matched.
-
makeSameHeightMax
Makes all specified elements the same height, matching the tallest element on page load.- Parameters:
elements- The elements to resize to match the tallest.
-
makeSameHeightMin
Makes all specified elements the same height, matching the shortest element on page load.- Parameters:
elements- The elements to resize to match the shortest.
-
makeSameWidth
Makes all specified elements the same width as the match element on page load.- Parameters:
elements- The elements to resize.match- The element whose width will be matched.
-
makeSameWidthMax
Makes all specified elements the same width, matching the widest element on page load.- Parameters:
elements- The elements to resize to match the widest.
-
makeSameWidthMin
Makes all specified elements the same width, matching the narrowest element on page load.- Parameters:
elements- The elements to resize to match the narrowest.
-
initializeFile
protected final boolean initializeFile()Initializes this page when first requested by the client.Sets up the page ID, cookies, session tracking, and delegates to
initializePage()for custom initialization logic.- Overrides:
initializeFilein classHttpFile- Returns:
trueif initialization succeeded,falseto abort page processing.
-
initializePage
protected boolean initializePage()Initializes this page for the current request.Subclasses can override this method to perform custom initialization logic such as access control checks, data loading, or session setup. Return
falseto abort page processing.- Returns:
- true if initialization was successful, false to abort
-
createFile
protected final void createFile()Creates the HTML structure of this page including head, body, scripts, and styles.Delegates to
createHead(Head)andcreateBody(Body)for page-specific content. After creation, initializes all child elements and runs post-creation hooks.- Specified by:
createFilein classHttpFile
-
createHead
Creates the head section of this page.Subclasses must implement this method to add stylesheets, scripts, meta tags, and other head content.
- Parameters:
head- The Head element to populate.
-
createBody
Creates the body section of this page.Subclasses must implement this method to build the page layout and content.
- Parameters:
body- The Body element to populate.
-
toString
Generates the complete HTML document string including the DOCTYPE declaration. -
sendUpdate
public void sendUpdate()Sends pending updates to the client using the configured communication mode.Routes updates to the appropriate transport based on the page's communication mode: WebSocket, SSE, or queues for AJAX polling.
For AJAX modes, this method commits the current thread's updates to the shared queue, making them available for the next poll or SSE push. This ensures that updates from worker threads are not sent until the thread explicitly signals completion.
-
sendAjaxResponse
-
sendWebSocketMessage
public void sendWebSocketMessage() -
sendSseMessage
public void sendSseMessage()Sends pending updates to the client via the SSE connection. -
onWebsocketOpen
protected void onWebsocketOpen()Called when a WebSocket connection is opened for this page.Subclasses can override this method to perform actions when the WebSocket is established.
-
onWebsocketMessage
Called when a WebSocket message is received from the client.Subclasses can override this method to handle raw WebSocket messages.
- Parameters:
msg- The raw message string received from the client.
-
onWebsocketError
Called when a WebSocket error occurs for this page.Subclasses can override this method to handle WebSocket errors.
- Parameters:
error- The error that occurred on the WebSocket connection.
-
onWebsocketClose
Called when the WebSocket connection for this page is closed.Subclasses can override this method to handle WebSocket disconnections.
- Parameters:
reason- The reason the WebSocket was closed.
-
onSseOpen
protected void onSseOpen()Called when an SSE connection is opened for this page.Subclasses can override this method to perform actions when the SSE connection is established.
-
onSseClose
protected void onSseClose()Called when the SSE connection for this page is closed.Subclasses can override this method to perform cleanup or other actions when the SSE connection is closed.
-
onSessionExpired
protected void onSessionExpired()Called when the user's session has expired during a WebSocket message.Subclasses can override this method to redirect the user or display a message.
-
onRequest
Subclasses should override this method if they need to do any pre-processing before a request is processed by the framework and passed on to application level classes.- Parameters:
request-response-
-
onLoaded
protected void onLoaded()Called when the page has finished loading in the browser.Subclasses can override this method to perform actions after the page is fully loaded.
-
onUnloaded
protected void onUnloaded()Called when the page is unloaded from the browser.Subclasses can override this method to perform cleanup when the user leaves the page.
-
onRefresh
protected void onRefresh()Called when the page is refreshed viarefresh().Subclasses can override this method to perform actions before child elements are refreshed.
-
onScreenResize
protected void onScreenResize()Called when the client's screen size changes.Subclasses can override this method to respond to screen orientation or resolution changes.
-
onWindowResize
protected void onWindowResize()Called when the browser window (viewport) is resized.Subclasses can override this method to adjust layout in response to window size changes.
-
onDocumentResize
protected void onDocumentResize()Called when the HTML document dimensions change.Subclasses can override this method to respond to document size changes caused by content additions or removals.
-
onCallback
Called when a client-side callback is triggered.Subclasses can override this method to handle custom client-to-server callbacks.
- Parameters:
callbackId- The identifier of the callback being invoked.
-
onJsReturn
Called when a JavaScript function returns a value to the server for a specific element.Subclasses can override this method to process JavaScript return values.
- Parameters:
elementId- The ID of the element associated with the JavaScript call.callbackId- The identifier of the callback.retval- The return value from the JavaScript function.
-
onJsReturn
Called when a JavaScript function returns a value to the server.Subclasses can override this method to process JavaScript return values.
- Parameters:
callbackId- The identifier of the callback.retval- The return value from the JavaScript function.
-
onUserEvent
Called when a custom user event is received from the client.Subclasses can override this method to handle application-specific client events.
- Parameters:
params- The parameters sent with the user event.
-
onClientDataEvent
Called when a client data event is received from the browser.Subclasses can override this method to handle data sent from client-side scripts.
- Parameters:
params- The parameters containing the client data.
-
onResponseComplete
protected void onResponseComplete()Called after a response has been successfully sent to the client.Subclasses can override this method to perform post-response actions such as logging or cleanup.
-
onException
Called when an exception occurs during page creation or processing.Subclasses can override this method to handle exceptions. Return
trueto re-throw the exception, orfalseto suppress it.- Parameters:
exception- The exception that occurred.- Returns:
trueto re-throw the exception,falseto suppress it.
-
getPageState
Returns the current lifecycle state of this page.- Returns:
- The current PageState.
-
getDisconnectedTime
public long getDisconnectedTime()Returns the time when the page became disconnected.- Returns:
- The disconnection timestamp in milliseconds, or 0 if the page is not disconnected.
-
getLastActivityTime
public long getLastActivityTime()Returns the time of the last activity on this page.- Returns:
- The last activity timestamp in milliseconds.
-
isDisconnectedTimeout
public boolean isDisconnectedTimeout(long timeoutMillis) Checks if the page has been disconnected longer than the specified timeout.- Parameters:
timeoutMillis- The timeout duration in milliseconds.- Returns:
- true if the page is disconnected and the timeout has expired, false otherwise.
-
addCookie
-
addCookie
-
addAttributeUpdate
-
addElementUpdate
-
addElementAddition
-
addElementSubtraction
-
addCommand
-
getPage
-
setCsrfProtectionEnabled(boolean)instead.