Class ServerMarkupContext

java.lang.Object
io.karatelabs.http.ServerMarkupContext
All Implemented Interfaces:
io.karatelabs.js.ObjectLike, io.karatelabs.js.SimpleObject, ActionDispatchHost, MarkupContext

public class ServerMarkupContext extends Object implements MarkupContext, ActionDispatchHost
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 Details

    • FLASH_SESSION_KEY

      public static final String FLASH_SESSION_KEY
      Session key used to persist flash messages across redirects.
      See Also:
  • Constructor Details

  • Method Details

    • setMarkupScope

      public void setMarkupScope(MarkupScope scope)
      Description copied from interface: MarkupContext
      Set the current-eval scope accessor. Called by MarkupTemplateContext at engine-bind time so context.get can resolve names from _ and the wrapped Thymeleaf scope. Default no-op for implementations that don't carry scope state.
      Specified by:
      setMarkupScope in interface MarkupContext
    • getMarkupScope

      public MarkupScope getMarkupScope()
      Description copied from interface: MarkupContext
      Companion accessor for MarkupContext.setMarkupScope(MarkupScope). Default returns null; implementations override to surface the scope to the context.get dispatch path.
      Specified by:
      getMarkupScope in interface MarkupContext
    • toVars

      public Map<String,Object> toVars()
      Build the standard variables map for template rendering. Includes global variables, request, response, context, and session.
    • getTemplateName

      public String getTemplateName()
      Description copied from interface: MarkupContext
      Returns the current template name (without leading slash).
      Specified by:
      getTemplateName in interface MarkupContext
    • getCallerTemplateName

      public String getCallerTemplateName()
      Description copied from interface: MarkupContext
      Returns the caller template name (for fragments/includes), or null if top-level.
      Specified by:
      getCallerTemplateName in interface MarkupContext
    • read

      public String read(String path)
      Description copied from interface: MarkupContext
      Read a resource as text.
      Specified by:
      read in interface MarkupContext
      Parameters:
      path - resource path (relative to template root or absolute)
      Returns:
      text content of the resource
    • readBytes

      public byte[] readBytes(String path)
      Description copied from interface: MarkupContext
      Read a resource as bytes.
      Specified by:
      readBytes in interface MarkupContext
      Parameters:
      path - resource path (relative to template root or absolute)
      Returns:
      byte array content of the resource
    • toJson

      public String toJson(Object obj)
      Description copied from interface: MarkupContext
      Serialize an object to JSON string.
      Specified by:
      toJson in interface MarkupContext
      Parameters:
      obj - object to serialize
      Returns:
      JSON string
    • fromJson

      public Object fromJson(String json)
      Description copied from interface: MarkupContext
      Parse a JSON string into an object (Map or List).
      Specified by:
      fromJson in interface MarkupContext
      Parameters:
      json - JSON string
      Returns:
      parsed object
    • getContextSession

      public Object getContextSession()
      Description copied from interface: MarkupContext
      Returns 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:
      getContextSession in interface MarkupContext
    • redirect

      public void redirect(String path)
      Set redirect path. This will cause a 302 redirect response.

      Throws a TemplateFlowSignal so 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 the redirectPath state set here.

    • log

      public void log(Object... args)
      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

      public String 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 reference session do so through JsLazy (see toVars() and ServerRequestCycle.createEngine()), so no callback is needed — the next access reads the live value.
    • close

      public void close()
      Close/invalidate the current session.
    • switchTemplate

      public void switchTemplate(String template)
      Switch to a different template for rendering.

      Throws a TemplateFlowSignal so 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 renders switchTemplate in place of the original.

    • setGlobal

      public void setGlobal(String name, Object value)
      Per-request escape hatch for setting JS-engine globals from inside a ka:scope="local" block. Routes to engine.put(name, value) so the value becomes a script-level global for the rest of the request, visible as a bare JS name in any subsequent eval (local or global) and via context.getGlobal(name).

      Distinct from context.set (which writes to _, the per-template-render namespace). Use setGlobal only when a value needs to cross template renders within a request (e.g. content → shell).

      No-op when no engine is wired (non-server contexts).

    • getGlobal

      public Object getGlobal(String name, Object defaultValue)
      Per-request engine-binding read with optional default. Symmetric reader for setGlobal(String, Object). Returns the engine binding's value if set (non-null), else the default (or null when no default is given). Returns null when no engine is wired.
    • jsGet

      public Object jsGet(String key)
      Description copied from interface: MarkupContext
      Default implementation of jsGet that exposes context methods to JavaScript. Implementations can override to add more properties/methods.
      Specified by:
      jsGet in interface MarkupContext
      Specified by:
      jsGet in interface io.karatelabs.js.SimpleObject
    • getRequest

      public HttpRequest getRequest()
    • getResponse

      public HttpResponse getResponse()
    • getConfig

      public ServerConfig getConfig()
    • getSession

      public Session getSession()
    • setSession

      public void setSession(Session session)
    • setTemplateName

      public void setTemplateName(String templateName)
    • setCallerTemplateName

      public void setCallerTemplateName(String callerTemplateName)
    • setResourceResolver

      public void setResourceResolver(Function<String,io.karatelabs.common.Resource> resourceResolver)
    • setEngine

      public void setEngine(io.karatelabs.js.Engine engine)
      Wired by ServerRequestCycle.createEngine() so setGlobal(String, Object) / getGlobal(String, Object) can route to the per-request JS engine bindings.
    • getEngine

      public io.karatelabs.js.Engine getEngine()
    • getRedirectPath

      public String getRedirectPath()
    • hasRedirect

      public boolean hasRedirect()
    • isClosed

      public boolean isClosed()
    • wasExplicitlyClosed

      public boolean wasExplicitlyClosed()
      True iff close() was explicitly called this request — distinct from the broader isClosed() which also returns true when there was never a session to begin with. Used by ServerRequestHandler to decide whether to emit a session-cookie-clear Set-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

      public String getSwitchTemplate()
    • getLogMessages

      public List<String> getLogMessages()
    • getFlash

      public Map<String,Object> getFlash()
    • getActions

      public Map<String,Object> getActions()
      Description copied from interface: ActionDispatchHost
      The (mutable) registry: action name → JS function. JS code populates this via context.actions['name'] = function(form){...}.
      Specified by:
      getActions in interface ActionDispatchHost
    • isActionDispatched

      public boolean isActionDispatched()
      Description copied from interface: ActionDispatchHost
      Whether this request's action handler has already been dispatched. The framework calls this before each potential dispatch attempt so the handler runs at most once per request.
      Specified by:
      isActionDispatched in interface ActionDispatchHost
    • markActionDispatched

      public void markActionDispatched()
      Description copied from interface: ActionDispatchHost
      Mark this request's action handler as dispatched. Called by the template engine after a successful dispatch.
      Specified by:
      markActionDispatched in interface ActionDispatchHost
    • setEagerDispatchHook

      public void setEagerDispatchHook(Consumer<String> hook)
      Description copied from interface: ActionDispatchHost
      Hook installed by the template engine; invoked by the host's context.actions view every time a key is set. Lets the engine dispatch the matching handler eagerly — i.e. as soon as it is registered — so any state reads later in the same script block observe post-mutation data. No-op default keeps non-server (plain templating) contexts simple.
      Specified by:
      setEagerDispatchHook in interface ActionDispatchHost
    • 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

      public CsrfProtection.CsrfToken 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