Class ContextHandler

All Implemented Interfaces:
Supplier<Handler>, Handler, HandlerContainer, Attributes, Container, Destroyable, Dumpable, Dumpable.DumpableContainer, LifeCycle
Direct Known Subclasses:
ServletContextHandler

@ManagedObject("EE9 Context") public class ContextHandler extends ScopedHandler implements Attributes, Supplier<Handler>
ContextHandler.

This handler wraps a call to handle by setting the context and servlet path, plus setting the context classloader.

If the context init parameter org.eclipse.jetty.server.context.ManagedAttributes is set to a comma separated list of names, then they are treated as context attribute names, which if set as attributes are passed to the servers Container so that they may be managed with JMX.

The maximum size of a form that can be processed by this context is controlled by the system properties org.eclipse.jetty.server.Request.maxFormKeys and org.eclipse.jetty.server.Request.maxFormContentSize. These can also be configured with setMaxFormContentSize(int) and setMaxFormKeys(int)

The executor is made available via a context attributed org.eclipse.jetty.server.Executor.

By default, the context is created with the AllowedResourceAliasChecker which is configured to allow symlinks. If this alias checker is not required, then clearAliasChecks() or setAliasChecks(List) should be called.

This handler can be invoked in 2 different ways:
  • Field Details

  • Constructor Details

  • Method Details

    • getCurrentContext

      public static ContextHandler.APIContext getCurrentContext()
      Get the current ServletContext implementation.
      Returns:
      ServletContext implementation
    • getCurrentContextHandler

      public static ContextHandler getCurrentContextHandler()
    • getContextHandler

      public static ContextHandler getContextHandler(jakarta.servlet.ServletContext context)
    • getServletContext

      public static jakarta.servlet.ServletContext getServletContext(Context context)
    • get

      public Handler get()
      Specified by:
      get in interface Supplier<Handler>
    • getCoreContextHandler

      public ContextHandler.CoreContextHandler getCoreContextHandler()
    • insertHandler

      public void insertHandler(Handler.Singleton coreHandler)
      Insert a handler between the getCoreContextHandler() and this handler.
      Parameters:
      coreHandler - A core handler to insert
    • dump

      public void dump(Appendable out, String indent) throws IOException
      Description copied from interface: Dumpable
      Dump this object (and children) into an Appendable using the provided indent after any new lines. The indent should not be applied to the first object dumped.
      Specified by:
      dump in interface Dumpable
      Overrides:
      dump in class ContainerLifeCycle
      Parameters:
      out - The appendable to dump to
      indent - The indent to apply after any new lines.
      Throws:
      IOException - if unable to write to Appendable
    • getServletContext

      public ContextHandler.APIContext getServletContext()
    • getAllowNullPathInfo

      @ManagedAttribute("Checks if the /context is not redirected to /context/") public boolean getAllowNullPathInfo()
      Returns:
      the allowNullPathInfo true if /context is not redirected to /context/
    • setAllowNullPathInfo

      public void setAllowNullPathInfo(boolean allowNullPathInfo)
      Set true if /context is not redirected to /context/.
      Parameters:
      allowNullPathInfo - true if /context is not redirected to /context/
    • setCrossContextDispatchSupported

      public void setCrossContextDispatchSupported(boolean supported)
      Cross context dispatch support.
      Parameters:
      supported - True if cross context dispatch is supported
      See Also:
    • isCrossContextDispatchSupported

      public boolean isCrossContextDispatchSupported()
      Cross context dispatch support.
      Returns:
      True if cross context dispatch is supported
      See Also:
    • setServer

      public void setServer(Server server)
      Specified by:
      setServer in interface Handler
      Overrides:
      setServer in class AbstractHandlerContainer
    • isUsingSecurityManager

      public boolean isUsingSecurityManager()
    • setUsingSecurityManager

      public void setUsingSecurityManager(boolean usingSecurityManager)
    • setVirtualHosts

      public void setVirtualHosts(String[] vhosts)
    • addVirtualHosts

      public void addVirtualHosts(String[] virtualHosts)
    • removeVirtualHosts

      public void removeVirtualHosts(String[] virtualHosts)
    • getVirtualHosts

      @ManagedAttribute(value="Virtual hosts accepted by the context", readonly=true) public String[] getVirtualHosts()
    • getAttribute

      public Object getAttribute(String name)
      Description copied from interface: Attributes
      Get an attribute
      Specified by:
      getAttribute in interface Attributes
      Parameters:
      name - the attribute to get
      Returns:
      the value of the attribute, or null if no such attribute exists
    • getAttributeNames

      public Enumeration<String> getAttributeNames()
    • getAttributeNameSet

      public Set<String> getAttributeNameSet()
      Description copied from interface: Attributes
      Get the immutable set of attribute names.
      Specified by:
      getAttributeNameSet in interface Attributes
      Returns:
      Set of attribute names, or an empty set if there are no attributes.
    • getAttributes

      public Attributes getAttributes()
      Returns:
      Returns the attributes.
    • getClassLoader

      public ClassLoader getClassLoader()
      Returns:
      Returns the classLoader.
    • getClassPath

      @ManagedAttribute("The file classpath") public String getClassPath()
      Make best effort to extract a file classpath from the context classloader
      Returns:
      Returns the classLoader.
    • getContextPath

      @ManagedAttribute("True if URLs are compacted to replace the multiple \'/\'s with a single \'/\'") public String getContextPath()
      Returns:
      Returns the contextPath.
    • getContextPathEncoded

      public String getContextPathEncoded()
      Returns:
      Returns the encoded contextPath.
    • getRequestContextPath

      public String getRequestContextPath()
      Get the context path in a form suitable to be returned from HttpServletRequest.getContextPath() or ServletContext.getContextPath().
      Returns:
      Returns the encoded contextPath, or empty string for root context
    • getInitParameter

      public String getInitParameter(String name)
    • setInitParameter

      public String setInitParameter(String name, String value)
    • getInitParameterNames

      public Enumeration<String> getInitParameterNames()
    • getInitParams

      @ManagedAttribute("Initial Parameter map for the context") public Map<String,String> getInitParams()
      Returns:
      Returns the initParams.
    • getDisplayName

      @ManagedAttribute(value="Display name of the Context", readonly=true) public String getDisplayName()
    • addEventListener

      public boolean addEventListener(EventListener listener)
      Add a context event listeners.
      Specified by:
      addEventListener in interface Container
      Specified by:
      addEventListener in interface LifeCycle
      Overrides:
      addEventListener in class ContainerLifeCycle
      Parameters:
      listener - the event listener to add
      Returns:
      true if the listener was added
      See Also:
    • removeEventListener

      public boolean removeEventListener(EventListener listener)
      Description copied from interface: Container
      Remove an event listener.
      Specified by:
      removeEventListener in interface Container
      Specified by:
      removeEventListener in interface LifeCycle
      Overrides:
      removeEventListener in class ContainerLifeCycle
      Parameters:
      listener - the listener to remove
      Returns:
      true if the listener was removed
      See Also:
    • addProgrammaticListener

      protected void addProgrammaticListener(EventListener listener)
      Apply any necessary restrictions on a programmatic added listener.
      Parameters:
      listener - the programmatic listener to add
    • isProgrammaticListener

      public boolean isProgrammaticListener(EventListener listener)
    • isDurableListener

      public boolean isDurableListener(EventListener listener)
    • isAvailable

      public boolean isAvailable()
      Returns:
      false if this context is unavailable (sends 503)
    • setAvailable

      public void setAvailable(boolean available)
      Set Available status.
      Parameters:
      available - true to set as enabled
    • getLogger

      public org.slf4j.Logger getLogger()
    • setLogger

      public void setLogger(org.slf4j.Logger logger)
    • doStart

      protected void doStart() throws Exception
      Description copied from class: ContainerLifeCycle
      Starts the managed lifecycle beans in the order they were added.
      Overrides:
      doStart in class ScopedHandler
      Throws:
      Exception - If there was a problem starting. Will cause a transition to FAILED state
    • doStartInContext

      protected void doStartInContext() throws Exception
      Throws:
      Exception
    • doStop

      protected void doStop() throws Exception
      Description copied from class: ContainerLifeCycle
      Stops the managed lifecycle beans in the reverse order they were added.
      Overrides:
      doStop in class AbstractHandler
      Throws:
      Exception - If there was a problem stopping. Will cause a transition to FAILED state
    • doStopInContext

      protected void doStopInContext() throws Exception
      Throws:
      Exception
    • startContext

      protected void startContext() throws Exception
      Extensible startContext. this method is called from doStart() instead of a call to super.doStart(). This allows derived classes to insert additional handling (Eg configuration) before the call to super.doStart by this method will start contained handlers.
      Throws:
      Exception - if unable to start the context
      See Also:
    • contextInitialized

      public void contextInitialized() throws Exception
      Call the ServletContextListeners contextInitialized methods. This can be called from a ServletHandler during the proper sequence of initializing filters, servlets and listeners. However, if there is no ServletHandler, the ContextHandler will call this method during doStart().
      Throws:
      Exception
    • contextDestroyed

      public void contextDestroyed() throws Exception
      Call the ServletContextListeners with contextDestroyed. This method can be called from a ServletHandler in the proper sequence of destroying filters, servlets and listeners. If there is no ServletHandler, the ContextHandler must ensure these listeners are called instead.
      Throws:
      Exception
    • stopContext

      protected void stopContext() throws Exception
      Throws:
      Exception
    • callContextInitialized

      protected void callContextInitialized(jakarta.servlet.ServletContextListener l, jakarta.servlet.ServletContextEvent e)
    • callContextDestroyed

      protected void callContextDestroyed(jakarta.servlet.ServletContextListener l, jakarta.servlet.ServletContextEvent e)
    • doScope

      public void doScope(String target, Request baseRequest, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws IOException, jakarta.servlet.ServletException
      Description copied from class: ScopedHandler
      Scope the handler

      Derived implementations should call ScopedHandler.nextScope(String, Request, HttpServletRequest, HttpServletResponse)

      Overrides:
      doScope in class ScopedHandler
      Parameters:
      target - The target of the request - either a URI or a name.
      baseRequest - The original unwrapped request object.
      request - The request either as the Request object or a wrapper of that request.
      response - The response as the Response object or a wrapper of that request.
      Throws:
      IOException - if unable to handle the request or response processing
      jakarta.servlet.ServletException - if unable to handle the request or response due to underlying servlet issue
    • requestInitialized

      protected void requestInitialized(Request baseRequest, jakarta.servlet.http.HttpServletRequest request)
    • requestDestroyed

      protected void requestDestroyed(Request baseRequest, jakarta.servlet.http.HttpServletRequest request)
    • doHandle

      public void doHandle(String target, Request baseRequest, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws IOException, jakarta.servlet.ServletException
      Description copied from class: ScopedHandler
      Do the handler work within the scope.

      Derived implementations should call ScopedHandler.nextHandle(String, Request, HttpServletRequest, HttpServletResponse)

      Specified by:
      doHandle in class ScopedHandler
      Parameters:
      target - The target of the request - either a URI or a name.
      baseRequest - The original unwrapped request object.
      request - The request either as the Request object or a wrapper of that request.
      response - The response as the Response object or a wrapper of that request.
      Throws:
      IOException - if unable to handle the request or response processing
      jakarta.servlet.ServletException - if unable to handle the request or response due to underlying servlet issue
    • enterScope

      protected void enterScope(Request request, Object reason)
      Parameters:
      request - A request that is applicable to the scope, or null
      reason - An object that indicates the reason the scope is being entered.
    • exitScope

      protected void exitScope(Request request)
      Parameters:
      request - A request that is applicable to the scope, or null
    • handle

      public void handle(Request request, Runnable runnable)
      Handle a runnable in the scope of this context and a particular request
      Parameters:
      request - The request to scope the thread to (may be null if no particular request is in scope)
      runnable - The runnable to run.
    • handle

      public void handle(Runnable runnable)
    • isProtectedTarget

      public boolean isProtectedTarget(String target)
      Check the target. Called by ScopedHandler.handle(String, Request, HttpServletRequest, HttpServletResponse) when a target within a context is determined. If the target is protected, 404 is returned.
      Parameters:
      target - the target to test
      Returns:
      true if target is a protected target
    • setProtectedTargets

      public void setProtectedTargets(String[] targets)
      Parameters:
      targets - Array of URL prefix. Each prefix is in the form /path and will match either /path exactly or /path/anything
    • getProtectedTargets

      public String[] getProtectedTargets()
    • removeAttribute

      public Object removeAttribute(String name)
      Description copied from interface: Attributes
      Remove an attribute
      Specified by:
      removeAttribute in interface Attributes
      Parameters:
      name - the attribute to remove
      Returns:
      the value of the attribute if removed, else null
    • setAttribute

      public Object setAttribute(String name, Object value)
      Description copied from interface: Attributes
      Set an attribute
      Specified by:
      setAttribute in interface Attributes
      Parameters:
      name - the attribute to set
      value - the value to set. A null value is equivalent to removing the attribute.
      Returns:
      the previous value of the attribute if set, else null
    • setAttributes

      public void setAttributes(Attributes attributes)
      Parameters:
      attributes - The attributes to set.
    • clearAttributes

      public void clearAttributes()
      Description copied from interface: Attributes
      Clear all attribute names
      Specified by:
      clearAttributes in interface Attributes
    • setClassLoader

      public void setClassLoader(ClassLoader classLoader)
      Parameters:
      classLoader - The classLoader to set.
    • setDefaultRequestCharacterEncoding

      public void setDefaultRequestCharacterEncoding(String encoding)
    • getDefaultRequestCharacterEncoding

      public String getDefaultRequestCharacterEncoding()
    • setDefaultResponseCharacterEncoding

      public void setDefaultResponseCharacterEncoding(String encoding)
    • getDefaultResponseCharacterEncoding

      public String getDefaultResponseCharacterEncoding()
    • setContextPath

      public void setContextPath(String contextPath)
      Parameters:
      contextPath - The _contextPath to set.
    • setDisplayName

      public void setDisplayName(String displayName)
      Parameters:
      displayName - The servletContextName to set.
    • getBaseResource

      @ManagedAttribute("document root for context") public Resource getBaseResource()
      Returns:
      Returns the resourceBase.
    • getResourceBase

      @Deprecated public String getResourceBase()
      Deprecated.
      use #getBaseResource()
      Returns:
      Returns the base resource as a string.
    • setBaseResource

      public void setBaseResource(Resource base)
      Set the base resource for this context.
      Parameters:
      base - The resource used as the base for all static content of this context.
    • setBaseResourceAsPath

      public void setBaseResourceAsPath(Path base)
      Set the base resource for this context.
      Parameters:
      base - The resource used as the base for all static content of this context.
      See Also:
    • setBaseResourceAsString

      public void setBaseResourceAsString(String base)
      Set the base resource for this context.
      Parameters:
      base - The resource used as the base for all static content of this context.
      See Also:
    • setResourceBase

      @Deprecated public void setResourceBase(String resourceBase)
      Deprecated.
      use #setBaseResource
      Set the base resource for this context.
      Parameters:
      resourceBase - A string representing the base resource for the context. Any string accepted by ResourceFactory.newResource(String) may be passed and the call is equivalent to setBaseResource(newResource(resourceBase));
    • getMimeTypes

      public MimeTypes.Mutable getMimeTypes()
      Returns:
      Returns the mimeTypes.
    • setWelcomeFiles

      public void setWelcomeFiles(String[] files)
    • getWelcomeFiles

      @ManagedAttribute(value="Partial URIs of directory welcome files", readonly=true) public String[] getWelcomeFiles()
      Returns:
      The names of the files which the server should consider to be welcome files in this context.
      See Also:
    • getErrorHandler

      @ManagedAttribute("The error handler to use for the context") public ErrorHandler getErrorHandler()
      Returns:
      Returns the errorHandler.
    • setErrorHandler

      public void setErrorHandler(ErrorHandler errorHandler)
      Parameters:
      errorHandler - The errorHandler to set.
    • getMaxFormContentSize

      @ManagedAttribute("The maximum content size") public int getMaxFormContentSize()
    • setMaxFormContentSize

      public void setMaxFormContentSize(int maxSize)
      Set the maximum size of a form post, to protect against DOS attacks from large forms.
      Parameters:
      maxSize - the maximum size of the form content (in bytes)
    • getMaxFormKeys

      public int getMaxFormKeys()
    • setMaxFormKeys

      public void setMaxFormKeys(int max)
      Set the maximum number of form Keys to protect against DOS attack from crafted hash keys.
      Parameters:
      max - the maximum number of form keys
    • isCompactPath

      @Deprecated(since="10.0.5", forRemoval=true) public boolean isCompactPath()
      Deprecated, for removal: This API element is subject to removal in a future version.
      use CompactPathRule with RewriteHandler instead. Will be removed from ee10 onwards.
      Is a compacted path used for context-path and url-pattern matching?
      Returns:
      True if URLs are compacted to replace multiple '/'s with a single '/'
      See Also:
    • setCompactPath

      @Deprecated(since="10.0.5", forRemoval=true) public void setCompactPath(boolean compactPath)
      Deprecated, for removal: This API element is subject to removal in a future version.
      use CompactPathRule with RewriteHandler instead. Will be removed from ee10 onwards.

      When performing context-path and url-pattern matching, do so with a compacted form of the request path.

      Note: this compacted path is not exposed to the Servlet API, the original request path is used.

      Parameters:
      compactPath - True if URLs are compacted to replace multiple '/'s with a single '/'
      See Also:
    • toString

      public String toString()
      Overrides:
      toString in class AbstractLifeCycle
    • loadClass

      public Class<?> loadClass(String className) throws ClassNotFoundException
      Throws:
      ClassNotFoundException
    • addLocaleEncoding

      public void addLocaleEncoding(String locale, String encoding)
    • getLocaleEncoding

      public String getLocaleEncoding(String locale)
    • getLocaleEncoding

      public String getLocaleEncoding(Locale locale)
      Get the character encoding for a locale. The full locale name is first looked up in the map of encodings. If no encoding is found, then the locale language is looked up.
      Parameters:
      locale - a Locale value
      Returns:
      a String representing the character encoding for the locale or null if none found.
    • getLocaleEncodings

      public Map<String,String> getLocaleEncodings()
      Get all of the locale encodings
      Returns:
      a map of all the locale encodings: key is name of the locale and value is the char encoding
    • getResource

      public Resource getResource(String pathInContext) throws MalformedURLException
      Attempt to get a Resource from the Context.
      Parameters:
      pathInContext - the path within the base resource to attempt to get
      Returns:
      the resource, or null if not available.
      Throws:
      MalformedURLException - if unable to form a Resource from the provided path
    • checkAlias

      public boolean checkAlias(String path, Resource resource)
      Parameters:
      path - the path to check the alias for
      resource - the resource
      Returns:
      True if the alias is OK
    • newResource

      public Resource newResource(URL url) throws IOException
      Convert URL to Resource wrapper for ResourceFactory.newResource(URL) enables extensions to provide alternate resource implementations.
      Parameters:
      url - the url to convert to a Resource
      Returns:
      the Resource for that url
      Throws:
      IOException - if unable to create a Resource from the URL
    • newResource

      public Resource newResource(URI uri) throws IOException
      Convert URL to Resource wrapper for ResourceFactory.newResource(URL) enables extensions to provide alternate resource implementations.
      Parameters:
      uri - the URI to convert to a Resource
      Returns:
      the Resource for that URI
      Throws:
      IOException - if unable to create a Resource from the URL
    • newResource

      public Resource newResource(String uriOrPath) throws IOException
      Convert a URL or path to a Resource. The default implementation is a wrapper for ResourceFactory.newResource(String).
      Parameters:
      uriOrPath - The URL or path to convert
      Returns:
      The Resource for the URL/path
      Throws:
      IOException - The Resource could not be created.
    • getResourcePaths

      public Set<String> getResourcePaths(String path)
    • addAliasCheck

      public void addAliasCheck(AliasCheck check)
      Add an AliasCheck instance to possibly permit aliased resources
      Parameters:
      check - The alias checker
    • getAliasChecks

      public List<AliasCheck> getAliasChecks()
      Returns:
      Immutable list of Alias checks
    • setAliasChecks

      public void setAliasChecks(List<AliasCheck> checks)
      Set list of AliasCheck instances.
      Parameters:
      checks - list of AliasCheck instances
    • clearAliasChecks

      public void clearAliasChecks()
      clear the list of AliasChecks
    • handle

      public void handle(HttpChannel channel) throws IOException, jakarta.servlet.ServletException
      Throws:
      IOException
      jakarta.servlet.ServletException
    • handleOptions

      protected void handleOptions(Request request, Response response) throws IOException
      Throws:
      IOException
    • handleAsync

      public void handleAsync(HttpChannel channel) throws IOException, jakarta.servlet.ServletException
      Throws:
      IOException
      jakarta.servlet.ServletException
    • getNestedResourceForTempDirName

      public Resource getNestedResourceForTempDirName()