Package io.karatelabs.http
Class ServerMarkupContext
java.lang.Object
io.karatelabs.http.ServerMarkupContext
- All Implemented Interfaces:
io.karatelabs.js.ObjectLike,io.karatelabs.js.SimpleObject,MarkupContext
Server-side context exposed to templates and API handlers.
Implements MarkupContext for template compatibility and adds server-specific methods.
In templates and API handlers, access via the 'context' variable:
<script ka:scope="global">
context.log('Processing request');
if (!session.user) {
context.redirect('/signin');
}
var id = context.uuid();
</script>
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringSession key used to persist flash messages across redirects.Fields inherited from interface io.karatelabs.js.SimpleObject
logger, TO_STRING -
Constructor Summary
ConstructorsConstructorDescriptionServerMarkupContext(HttpRequest request, HttpResponse response, ServerConfig config) -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Close/invalidate the current session.Parse a JSON string into an object (Map or List).Returns the caller template name (for fragments/includes), or null if top-level.Returns the session object if one exists, null otherwise.Get the CSRF token object for templates.getFlash()Returns the current template name (without leading slash).booleanvoidinit()Initialize a new session.booleanisAjax()Check if this is an AJAX/HTMX request.booleanisClosed()booleanDefault implementation of jsGet that exposes context methods to JavaScript.voidLoad flash messages from session (if any) and clear them from session.voidLog a message.voidPersist current flash messages to session.Read a resource as text.byte[]Read a resource as bytes.voidSet redirect path.voidsetCallerTemplateName(String callerTemplateName) voidsetResourceResolver(Function<String, io.karatelabs.common.Resource> resourceResolver) voidsetSession(Session session) voidsetTemplateName(String templateName) voidswitchTemplate(String template) Switch to a different template for rendering.Serialize an object to JSON string.toVars()Build the standard variables map for template rendering.uuid()Generate a new UUID string.booleanTrue iffclose()was explicitly called this request — distinct from the broaderisClosed()which also returns true when there was never a session to begin with.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface io.karatelabs.js.ObjectLike
getPrototypeMethods inherited from interface io.karatelabs.js.SimpleObject
getMember, jsKeys, jsToString, putMember, removeMember, toMap
-
Field Details
-
FLASH_SESSION_KEY
Session key used to persist flash messages across redirects.- See Also:
-
-
Constructor Details
-
ServerMarkupContext
-
-
Method Details
-
toVars
Build the standard variables map for template rendering. Includes global variables, request, response, context, and session. -
getTemplateName
Description copied from interface:MarkupContextReturns the current template name (without leading slash).- Specified by:
getTemplateNamein interfaceMarkupContext
-
getCallerTemplateName
Description copied from interface:MarkupContextReturns the caller template name (for fragments/includes), or null if top-level.- Specified by:
getCallerTemplateNamein interfaceMarkupContext
-
read
Description copied from interface:MarkupContextRead a resource as text.- Specified by:
readin interfaceMarkupContext- Parameters:
path- resource path (relative to template root or absolute)- Returns:
- text content of the resource
-
readBytes
Description copied from interface:MarkupContextRead a resource as bytes.- Specified by:
readBytesin interfaceMarkupContext- Parameters:
path- resource path (relative to template root or absolute)- Returns:
- byte array content of the resource
-
toJson
Description copied from interface:MarkupContextSerialize an object to JSON string.- Specified by:
toJsonin interfaceMarkupContext- Parameters:
obj- object to serialize- Returns:
- JSON string
-
fromJson
Description copied from interface:MarkupContextParse a JSON string into an object (Map or List).- Specified by:
fromJsonin interfaceMarkupContext- Parameters:
json- JSON string- Returns:
- parsed object
-
getContextSession
Description copied from interface:MarkupContextReturns the session object if one exists, null otherwise. Used by template engine to sync session variable after context.init() is called. Default returns null (no session in plain templating mode).- Specified by:
getContextSessionin interfaceMarkupContext
-
redirect
Set redirect path. This will cause a 302 redirect response.Throws a
TemplateFlowSignalso the current template render or API handler evaluation is aborted cleanly (no further statements run, no downstream template errors logged). The signal is caught silently by the server request cycle; the actual redirect is driven by theredirectPathstate set here. -
log
Log a message. Messages are captured and can be retrieved via getLogMessages(). If a logHandler is configured in ServerConfig, it will be called. Otherwise, falls back to System.out.println. -
uuid
Generate a new UUID string. -
init
public void init()Initialize a new session. If sessions are not enabled in config, this is a no-op. Script and template bindings that referencesessiondo so through a Supplier (seetoVars()andServerRequestCycle.createEngine()), so no callback is needed — the next access reads the live value. -
close
public void close()Close/invalidate the current session. -
switchTemplate
Switch to a different template for rendering.Throws a
TemplateFlowSignalso the current template render is aborted cleanly (the original template is abandoned; the new one is rendered instead). The signal is caught silently by the server request cycle, which then rendersswitchTemplatein place of the original. -
jsGet
Description copied from interface:MarkupContextDefault implementation of jsGet that exposes context methods to JavaScript. Implementations can override to add more properties/methods.- Specified by:
jsGetin interfaceMarkupContext- Specified by:
jsGetin interfaceio.karatelabs.js.SimpleObject
-
getRequest
-
getResponse
-
getConfig
-
getSession
-
setSession
-
setTemplateName
-
setCallerTemplateName
-
setResourceResolver
-
getRedirectPath
-
hasRedirect
public boolean hasRedirect() -
isClosed
public boolean isClosed() -
wasExplicitlyClosed
public boolean wasExplicitlyClosed()True iffclose()was explicitly called this request — distinct from the broaderisClosed()which also returns true when there was never a session to begin with. Used byServerRequestHandlerto decide whether to emit a session-cookie-clearSet-Cookie(defense-in-depth signout: server-side record is gone, so make sure the client's stale cookie is gone too). -
isSwitched
public boolean isSwitched() -
getSwitchTemplate
-
getLogMessages
-
getFlash
-
loadFlashFromSession
public void loadFlashFromSession()Load flash messages from session (if any) and clear them from session. Called at the start of request processing to retrieve messages set before a redirect. -
persistFlashToSession
public void persistFlashToSession()Persist current flash messages to session. Called before redirect so messages survive to the next request. -
isAjax
public boolean isAjax()Check if this is an AJAX/HTMX request. -
getCsrfToken
Get the CSRF token object for templates. Returns a CsrfToken with token, headerName, and fieldName properties.- Returns:
- CsrfToken object or null if CSRF is disabled or no session
-