Package groovy.servlet

# Class AbstractHttpServlet

java.lang.Object
jakarta.servlet.GenericServlet
jakarta.servlet.http.HttpServlet
groovy.servlet.AbstractHttpServlet

All Implemented Interfaces:
  `ResourceConnector`, `jakarta.servlet.Servlet`, `jakarta.servlet.ServletConfig`, `Serializable`

Direct Known Subclasses:
  `GroovyServlet`, `TemplateServlet`

public abstract class AbstractHttpServlet extends jakarta.servlet.http.HttpServlet implements ResourceConnector
A base class dealing with common HTTP servlet API housekeeping aspects.

#### Resource name mangling (pattern replacement)

Also implements Groovy's `ResourceConnector` in a dynamic manner. It allows you to modify the resource name that is searched for with a replace all operation. See `Pattern` and `Matcher` for details. The servlet init parameter names are:

     "resource.name.regex" = empty - defaults to null
     resource.name.replacement = empty - defaults to null
     resource.name.replace.all = true (default) | false means replaceFirst()

Note: If you specify a regex, you have to specify a replacement string too! Otherwise an exception gets raised.

#### Logging and bug-hunting options

This implementation provides a verbosity flag switching log statements. The servlet init parameter name is:

     verbose = false(default) | true

In order to support class-loading-troubles-debugging with Tomcat 4 or higher, you can log the class loader responsible for loading some classes. See GROOVY-861 for details. The servlet init parameter name is:

     log.GROOVY861 = false(default) | true

If you experience class-loading-troubles with Tomcat 4 (or higher) or any other servlet container using custom class loader setups, you can fall back to use (slower) reflection in Groovy's MetaClass implementation. Please contact the dev team with your problem! Thanks. The servlet init parameter name is:

     reflection = false(default) | true

Deployment security notes. The script/template path is resolved from the request URI via the servlet container's `getRealPath`/`getResource`; this class relies on the container to normalize `..` segments and reject path traversal, so operators must not expose an attacker-writable script root (a Groovlet/template is operator-deployed, trusted code). Response security headers such as `Strict-Transport-Security` (HSTS) and `Content-Security-Policy` are not emitted here — configure them at the TLS-terminating reverse proxy or servlet container.

See Also:
  - Serialized Form

- ## Field Summary

  Fields
  Modifier and Type
  Field
  Description
  `static final String`
  `CONTENT_TYPE_TEXT_HTML`
  Content type of the HTTP response.
  `protected String`
  `encoding`
  Encoding to use, becomes charset part of contentType.
  `static final String`
  `INC_PATH_INFO`
  Servlet API include key name: path_info
  `static final String`
  `INC_REQUEST_URI`
  Servlet API include key name for the original request URI.
  `static final String`
  `INC_SERVLET_PATH`
  Servlet API include key name: servlet_path
  `static final String`
  `INIT_PARAM_RESOURCE_NAME_REGEX`
  Init parameter defining the regular expression used to rewrite resource names.
  `static final String`
  `INIT_PARAM_RESOURCE_NAME_REGEX_FLAGS`
  Init parameter defining the numeric `Pattern` compile flags for the resource name regex.
  `protected String`
  `namePrefix`
  a.fink: it was in `removeNamePrefix(java.lang.String)`, but was extracted to var for optimization
  `protected boolean`
  `reflection`
  Mirrors the static value of the reflection flag in MetaClass.
  `protected Pattern`
  `resourceNamePattern`
  Either `null` or a compiled pattern read from ""resource.name.regex"" and used in `getScriptUri(HttpServletRequest)`.
  `protected boolean`
  `resourceNameReplaceAll`
  The replace method to use on the matcher.
  `protected String`
  `resourceNameReplacement`
  The replacement used by the resource name matcher.
  `protected jakarta.servlet.ServletContext`
  `servletContext`
  Servlet (or the web application) context.
  `protected boolean`
  `verbose`
  Controls almost all log output.

  ### Fields inherited from class jakarta.servlet.http.HttpServlet

  `LEGACY_DO_HEAD`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `AbstractHttpServlet()`
  Initializes all fields with default values.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `protected String`
  `applyResourceNameMatcher(String uri)`
  Applies the configured resource name rewrite pattern to the supplied URI.
  `protected void`
  `generateNamePrefixOnce()`
  Computes the servlet context base URL once and caches it in `namePrefix`.
  `URLConnection`
  `getResourceConnection(String name)`
  Interface method for ResourceContainer.
  `protected String`
  `getScriptUri(jakarta.servlet.http.HttpServletRequest request)`
  Returns the include-aware uri of the script or template file.
  `protected File`
  `getScriptUriAsFile(jakarta.servlet.http.HttpServletRequest request)`
  Parses the http request for the real script or template source file.
  `void`
  `init(jakarta.servlet.ServletConfig config)`
  Overrides the generic init method to set some debug flags.
  `protected String`
  `removeNamePrefix(String name)`
  Removes the cached servlet context prefix from a resource name when present.
  `protected void`
  `setVariables(ServletBinding binding)`
  Override this method to set your variables to the Groovy binding.

  ### Methods inherited from class jakarta.servlet.http.HttpServlet

  `doDelete, doGet, doHead, doOptions, doPatch, doPost, doPut, doTrace, getLastModified, isSensitiveHeader, service, service`

  ### Methods inherited from class jakarta.servlet.GenericServlet

  `destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, log, log`

  ### Methods inherited from class java.lang.Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Field Details

  - ### INIT_PARAM_RESOURCE_NAME_REGEX

    public static final String INIT_PARAM_RESOURCE_NAME_REGEX
    Init parameter defining the regular expression used to rewrite resource names.
    See Also:
      - Constant Field Values

  - ### INIT_PARAM_RESOURCE_NAME_REGEX_FLAGS

    public static final String INIT_PARAM_RESOURCE_NAME_REGEX_FLAGS
    Init parameter defining the numeric `Pattern` compile flags for the resource name regex.
    See Also:
      - Constant Field Values

  - ### CONTENT_TYPE_TEXT_HTML

    public static final String CONTENT_TYPE_TEXT_HTML
    Content type of the HTTP response.
    See Also:
      - Constant Field Values

  - ### INC_PATH_INFO

    public static final String INC_PATH_INFO
    Servlet API include key name: path_info
    See Also:
      - Constant Field Values

  - ### INC_REQUEST_URI

    public static final String INC_REQUEST_URI
    Servlet API include key name for the original request URI.

    Currently retained for completeness; see the notes in `getScriptUri(HttpServletRequest)`.

    See Also:
      - Constant Field Values

  - ### INC_SERVLET_PATH

    public static final String INC_SERVLET_PATH
    Servlet API include key name: servlet_path
    See Also:
      - Constant Field Values

  - ### servletContext

    protected jakarta.servlet.ServletContext servletContext
    Servlet (or the web application) context.

  - ### resourceNamePattern

    protected Pattern resourceNamePattern
    Either `null` or a compiled pattern read from ""resource.name.regex"" and used in `getScriptUri(HttpServletRequest)`.

  - ### resourceNameReplacement

    protected String resourceNameReplacement
    The replacement used by the resource name matcher.

  - ### resourceNameReplaceAll

    protected boolean resourceNameReplaceAll
    The replace method to use on the matcher.

         true - replaceAll(resourceNameReplacement); (default)
         false - replaceFirst(resourceNameReplacement);

  - ### verbose

    protected boolean verbose
    Controls almost all log output.

  - ### encoding

    protected String encoding
    Encoding to use, becomes charset part of contentType.

  - ### reflection

    protected boolean reflection
    Mirrors the static value of the reflection flag in MetaClass. See AbstractHttpServlet#logGROOVY861

  - ### namePrefix

    protected String namePrefix
    a.fink: it was in `removeNamePrefix(java.lang.String)`, but was extracted to var for optimization

- ## Constructor Details

  - ### AbstractHttpServlet

    public AbstractHttpServlet()
    Initializes all fields with default values.

- ## Method Details

  - ### generateNamePrefixOnce

    protected void generateNamePrefixOnce()
    Computes the servlet context base URL once and caches it in `namePrefix`.

  - ### removeNamePrefix

    protected String removeNamePrefix(String name) throws ResourceException
    Removes the cached servlet context prefix from a resource name when present.
    Parameters:
      `name` - the resource name to normalize
    Returns:
      the resource name without the servlet context prefix
    Throws:
      `ResourceException` - if resource normalization fails downstream

  - ### getResourceConnection

    public URLConnection getResourceConnection(String name) throws ResourceException
    Interface method for ResourceContainer. This is used by the GroovyScriptEngine.
    Specified by:
      `getResourceConnection` in interface `ResourceConnector`
    Throws:
      `ResourceException`

  - ### getScriptUri

    protected String getScriptUri(jakarta.servlet.http.HttpServletRequest request)
    Returns the include-aware uri of the script or template file.
    Parameters:
      `request` - the http request to analyze
    Returns:
      the include-aware uri either parsed from request attributes or hints provided by the servlet container

  - ### applyResourceNameMatcher

    protected String applyResourceNameMatcher(String uri)
    Applies the configured resource name rewrite pattern to the supplied URI.
    Parameters:
      `uri` - the request-relative URI to rewrite
    Returns:
      the rewritten URI, or the original value when no rewrite applies

  - ### getScriptUriAsFile

    protected File getScriptUriAsFile(jakarta.servlet.http.HttpServletRequest request)
    Parses the http request for the real script or template source file.
    Parameters:
      `request` - the http request to analyze
    Returns:
      a file object using an absolute file path name, or `null` if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

  - ### init

    public void init(jakarta.servlet.ServletConfig config) throws jakarta.servlet.ServletException
    Overrides the generic init method to set some debug flags.
    Specified by:
      `init` in interface `jakarta.servlet.Servlet`
    Overrides:
      `init` in class `jakarta.servlet.http.HttpServlet`
    Parameters:
      `config` - the servlet configuration provided by the container
    Throws:
      `jakarta.servlet.ServletException` - if init() method defined in super class javax.servlet.GenericServlet throws it

  - ### setVariables

    protected void setVariables(ServletBinding binding)
    Override this method to set your variables to the Groovy binding.

    All variables bound the binding are passed to the template source text, e.g. the HTML file, when the template is merged.

    The binding provided by TemplateServlet does already include some default variables. As of this writing, they are (copied from `ServletBinding`):

    - `"request"` : HttpServletRequest
    - `"response"` : HttpServletResponse
    - `"context"` : ServletContext
    - `"application"` : ServletContext
    - `"session"` : request.getSession(false)

    And via implicit hard-coded keywords:

    - `"out"` : response.getWriter()
    - `"sout"` : response.getOutputStream()
    - `"html"` : new MarkupBuilder(response.getWriter())

    The binding also provides convenient methods:

    - `"forward(String path)"` : request.getRequestDispatcher(path).forward(request, response);
    - `"include(String path)"` : request.getRequestDispatcher(path).include(request, response);
    - `"redirect(String location)"` : response.sendRedirect(location);

    Example binding all servlet context variables:

         class MyServlet extends TemplateServlet {

           protected void setVariables(ServletBinding binding) {
             // Bind a simple variable
             binding.setVariable("answer", new Long(42));

             // Bind all servlet context attributes...
             ServletContext context = (ServletContext) binding.getVariable("context");
             Enumeration enumeration = context.getAttributeNames();
             while (enumeration.hasMoreElements()) {
               String name = (String) enumeration.nextElement();
               binding.setVariable(name, context.getAttribute(name));
             }
           }
         }

    Parameters:
      `binding` - to be modified