servlet

fun Route.servlet(path: String, servlet: HttpServlet)

Mounts a Jakarta HttpServlet at the given path within a Ktor Route.

The servlet is initialized once via init(ServletConfig), as a servlet container would. The config is named after the servlet's class and has no init parameters. Its ServletContext supports attributes and logging, and throws UnsupportedOperationException for container features such as dynamic registration. Each incoming request is translated into a KtorServletRequest/KtorServletResponse pair. The servlet's response headers, status code, and body are then forwarded back through the Ktor response pipeline, with the character encoding the servlet used included in the Content-Type. A body sent without a content type, or with one that does not parse (which is logged as a warning naming the servlet, without the value), is labeled application/octet-stream; an empty body without a content type gets no Content-Type. Content-Length comes from the body actually sent, and the servlet's Content-Length, Transfer-Encoding and Upgrade headers are dropped. A 1xx, 204, 205 or 304 response, which carries no content, is sent without a body (whatever the servlet wrote is dropped), without a Content-Length (Ktor gives a 205 a Content-Length: 0), and with a Content-Type only when the servlet set a valid one. Servlet processing runs on kotlinx.coroutines.Dispatchers.IO. The servlet's destroy() is called when the application stops.

Log lines name the servlet by the name in the config it keeps once initialized, or by its class when it keeps none.

When the servlet throws (a kotlinx.coroutines.CancellationException included), or sets a header name or value that HTTP does not allow (one holding CR or LF, for example, in any header or in the content type), the client gets a 500 with an empty body and none of the servlet's headers, and the failure is logged at ERROR. A thrown exception is logged with its stack trace; an invalid header is logged by name, without its value. Ktor's default handler would have sent the exception's message, or the invalid value, as the body. Since the route answers these failures itself, StatusPages exception handlers do not see them, though a status handler for 500 still applies. When the call itself has been cancelled, its cancellation is rethrown instead, and so is a failure after the response has been committed, which Ktor logs without sending anything more.

Parameters

path

the URL path at which the servlet should be mounted

servlet

the Jakarta servlet instance to handle requests