Camel Components

Servlet

Since Camel 2.0

Only consumer is supported

The Servlet component provides HTTP-based endpoints for consuming HTTP requests that arrive at an HTTP endpoint that is bound to a published Servlet.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-servlet</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

Stream

Servlet is stream-based, which means the input it receives is submitted to Camel as a stream. By default the consumer copies the request body into a stream cache, which can be read more than once. With disableStreamCache=true the body is the raw request stream, and you will only be able to read the content of the stream once. If you find a situation where the message body appears to be empty, or you need to access the data multiple times (eg: doing multicasting, or redelivery error handling), you should use Stream caching or convert the message body to a String which is safe to be read multiple times.

URI format

servlet://relative_path[?options]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Servlet component supports the following options which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

muteException (consumer)

Whether to keep the exception out of the response when an exchange fails on a consumer: the response is the 500 status code with an empty body. It is the default of the muteException option of the endpoints.

true

boolean

servletName (consumer)

The default servletName of the endpoints: the name of the CamelHttpTransportServlet that receives the requests of the consumers, as its servlet name in the servlet container, such as the servlet-name in web.xml.

CamelServlet

String

attachmentMultipartBinding (consumer (advanced))

Whether to bind the parts of a multipart/form-data request as attachments on the Camel message, keyed by the part (form field) name and with the part headers as attachment headers. The parts are read with HttpServletRequest.getParts(), which the Servlet API allows only for a servlet with a multipart configuration (MultipartConfig, or multipart-config in web.xml), so configure one for the CamelHttpTransportServlet. Enabling it turns on disableStreamCache; an explicit disableStreamCache=false fails the endpoint creation. This is the default of the endpoints, also of the Rest DSL consumers.

false

boolean

fileNameExtWhitelist (consumer (advanced))

The accepted extensions of uploaded file names, without the dot and separated by comma, such as txt,xml. A file part of a multipart request with another extension is not bound as an attachment (see attachmentMultipartBinding). The extension is all after the first dot of the submitted file name (tar.gz for report.tar.gz) and is compared ignoring case. When not set, or set to *, every file is accepted. This is the default of the endpoints, also of the Rest DSL consumers.

String

httpRegistry (consumer (advanced))

A custom org.apache.camel.http.common.HttpRegistry that connects the consumers to the CamelHttpTransportServlet instances. When not set, each consumer registers in the shared registry of its servletName, where the CamelHttpTransportServlet of that name registers itself.

HttpRegistry

allowJavaSerializedObject (advanced)

Whether to allow Java serialization of a message body with Content-Type application/x-java-serialized-object: a consumer deserializes such a request body and can write a Java object as such a response, and the HTTP producer deserializes such a response body. When not allowed, such a body that is received is dropped (null). This is turned off by default: if you enable it, be aware that Java deserializes the data that the other side sends, which can be a security risk.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

httpBinding (advanced)

To use a custom HttpBinding for the consumers of this component, which reads the HTTP servlet request into the Camel message and writes the Camel message to the HTTP servlet response. The HTTP producer (camel-http) does not use it.

HttpBinding

httpConfiguration (advanced)

A shared HttpConfiguration with default options for the endpoints that this component creates; an option set on the endpoint takes precedence. Only the HTTP producer (camel-http) uses it, and only its authentication options (authMethod, which must be set, with the credentials) configure the HTTP client. The consumer components ignore it.

HttpConfiguration

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

deserializationFilter (security)

Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied when deserializing Java objects from requests or responses with Content-Type application/x-java-serialized-object (only used when allowJavaSerializedObject or transferException is enabled). When not set, the JVM-wide jdk.serialFilter is used if present; otherwise a default filter is applied that rejects java.net., allows java., javax.* and org.apache.camel.*, and rejects every other class.

String

Endpoint Options

The Servlet endpoint is configured using URI syntax:

servlet:contextPath

With the following path and query parameters:

Path Parameters

Name Description Default Type

contextPath (consumer)

Required The path that this consumer serves, relative to the URL mapping of the CamelHttpTransportServlet: it is matched against the path info of the request (HttpServletRequest.getPathInfo()), the part of the request path after the web application context path and the servlet path. A missing leading slash is added.

String

Query Parameters

Name Description Default Type

disableStreamCache (common)

Whether to turn off the caching of the raw HTTP stream. By default the consumer (camel-servlet, camel-jetty) copies the request body into a stream cache, so it can be read more than once, and the producer (camel-http) does the same with the response body. When true, the message body is the raw input stream, which can only be read once: use it to stream a large payload directly to a file or another store, or in a proxy route that does not read the body. The producer then closes the response stream when the exchange completes.

false

boolean

transferException (common)

If enabled and an exchange fails on the consumer, the consumer sends the exception back in the response as a Java serialized object, with Content-Type application/x-java-serialized-object, instead of its stack trace as text. It has no effect while muteException is enabled (the default). The exception must be serializable. It also makes the consumer deserialize a request body of that content type. This is turned off by default: if you enable it, be aware that Java deserializes the data that the client sends, which can be a security risk.

false

boolean

headerFilterStrategy (common (advanced))

To use a custom HeaderFilterStrategy to filter the headers that are mapped between the Camel message and the HTTP request and response.

HeaderFilterStrategy

httpBinding (common (advanced))

To use a custom HttpBinding that reads the HTTP servlet request into the Camel message and writes the Camel message to the HTTP servlet response. The options muteException, logException, transferException, eagerCheckContentAvailable and mapHttpMessage* of the endpoint only configure the binding that Camel creates, not a custom one.

HttpBinding

async (consumer)

Whether the consumer uses the Servlet asynchronous support: the request is put in asynchronous mode (AsyncContext), the route runs on another thread of the container, and the response is written when the exchange completes. Only camel-jetty uses this option; camel-servlet takes it from the async init parameter of the CamelHttpTransportServlet.

false

boolean

chunked (consumer)

If false, the consumer writes the response with a Content-Length header, which buffers the whole body first, instead of streaming it with chunked transfer encoding. The CamelHttpChunked message header overrides this option.

true

boolean

httpMethodRestrict (consumer)

Comma-separated list of the HTTP methods that the consumer accepts, such as GET,POST. A request with another method gets the 405 Method Not Allowed response.

String

logException (consumer)

Whether to log the exception, with its stack trace at ERROR level, when an exchange fails on the consumer and muteException keeps it out of the response.

false

boolean

matchOnUriPrefix (consumer)

Whether the consumer also serves the requests to paths below its own path (its path used as a URI prefix), when no consumer matches the request path exactly.

false

boolean

muteException (consumer)

Whether to keep the exception out of the response when an exchange fails on the consumer: the response is the 500 status code with an empty body. When false, the response body is the stack trace of the exception as text (or the serialized exception with transferException).

true

boolean

responseBufferSize (consumer)

The buffer size, in bytes, of the HTTP servlet response (ServletResponse.setBufferSize), which is also the size of the buffer used to copy the response body. When not set, the default of the servlet container is used.

Integer

servletName (consumer)

The name of the CamelHttpTransportServlet that receives the requests of this consumer: its servlet name in the servlet container, such as the servlet-name in web.xml.

CamelServlet

String

attachmentMultipartBinding (consumer (advanced))

Whether to bind the parts of a multipart/form-data request as attachments on the Camel message, keyed by the part (form field) name and with the part headers as attachment headers. The parts are read with HttpServletRequest.getParts(), which the Servlet API allows only for a servlet with a multipart configuration (MultipartConfig, or multipart-config in web.xml), so configure one for the CamelHttpTransportServlet. Enabling it turns on disableStreamCache; an explicit disableStreamCache=false fails the endpoint creation.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

eagerCheckContentAvailable (consumer (advanced))

Whether to check that the request input stream has data available when the request has no Content-Length header; the message body is null when no data is available right away. Turn it on for HTTP clients that do not stream the body. A request with Content-Length 0 always has a null body.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

fileNameExtWhitelist (consumer (advanced))

The accepted extensions of uploaded file names, without the dot and separated by comma, such as txt,xml. A file part of a multipart request with another extension is not bound as an attachment (see attachmentMultipartBinding). The extension is all after the first dot of the submitted file name (tar.gz for report.tar.gz) and is compared ignoring case. When not set, or set to *, every file is accepted.

String

mapHttpMessageBody (consumer (advanced))

If this option is true then the HTTP request body is mapped to the IN message body. If this option is false then the request body is not read and the message body is null, and no attachments, Java serialized objects or form fields are mapped.

true

boolean

mapHttpMessageFormUrlEncodedBody (consumer (advanced))

Whether to map the fields of a POST request with an application/x-www-form-urlencoded body to Camel message headers. It only applies when mapHttpMessageBody and mapHttpMessageHeaders are true too.

true

boolean

mapHttpMessageHeaders (consumer (advanced))

Whether to map the HTTP request headers and the request parameters (such as the query parameters) to Camel message headers, filtered by the headerFilterStrategy. When false, only the CamelHttp* headers (method, URI, URL, path and query) and Content-Type are set.

true

boolean

optionsEnabled (consumer (advanced))

Whether the consumer routes HTTP OPTIONS requests. When false, the consumer answers an OPTIONS request itself, with status 200 and an Allow header that lists the HTTP methods it accepts.

false

boolean

traceEnabled (consumer (advanced))

Whether the consumer accepts HTTP TRACE requests and routes them. When false, a TRACE request gets the 405 Method Not Allowed response.

false

boolean

oauthProfile (security)

OAuth profile name for validating incoming Authorization: Bearer tokens. When set, the request is authenticated before the route is processed. This requires an OAuthTokenValidationFactory; camel-oauth provides the default implementation. This is Camel endpoint-level validation and does not replace servlet container or framework security.

String

Message Headers

The Servlet component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelHttpMethod (consumer)

Constant: HTTP_METHOD

The HTTP method of the request, such as GET or POST.

String

CamelServletContextPath (consumer)

Constant: SERVLET_CONTEXT_PATH

The path of the endpoint that received the request (the contextPath of the endpoint URI), for example /hello for servlet:hello.

String

CamelHttpPath (consumer)

Constant: HTTP_PATH

The path of the request after the web application context path, the servlet path and the path of the endpoint (CamelServletContextPath), as received (not URL-decoded).

String

CamelHttpQuery (consumer)

Constant: HTTP_QUERY

The query string of the request (not URL-decoded), or null when it has none.

String

CamelHttpUri (consumer)

Constant: HTTP_URI

The URI of the request without the query string (HttpServletRequest.getRequestURI()), from the web application context path on.

String

CamelHttpUrl (consumer)

Constant: HTTP_URL

The URL of the request without the query string, with the scheme, host and port (HttpServletRequest.getRequestURL()).

String

CamelHttpCharacterEncoding (consumer)

Constant: HTTP_CHARACTER_ENCODING

The charset that the request declares (HttpServletRequest.getCharacterEncoding()). Set only when the request has one.

String

Content-Type (consumer)

Constant: CONTENT_TYPE

The Content-Type of the request. In the reply, the Content-Type of the response.

String

CamelHttpResponseCode (consumer)

Constant: HTTP_RESPONSE_CODE

The HTTP status code of the response. When it is not set, the response is 200, 204 when the reply has no body, or 500 when the exchange failed.

Integer

CamelHttpChunked (consumer)

Constant: HTTP_CHUNKED

Whether the response is written in chunked mode (Transfer-Encoding: chunked), overriding the chunked option.

Boolean

Content-Encoding (consumer)

Constant: CONTENT_ENCODING

The Content-Encoding of the request, which is copied to the reply. When the Content-Encoding of the reply contains gzip, the response body is written compressed with GZIP, unless bridgeEndpoint is enabled.

String

Message Body

The message body at each side of the Servlet component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

stream or null

The request body as a stream cache, which can be read again (the raw stream, read once, with disableStreamCache); an empty one for a GET, null with Content-Length 0 or eagerCheckContentAvailable. The fields of a form are also headers; a multipart request is the raw multipart payload, or with attachmentMultipartBinding an empty body and its parts as attachments.

Not known when transferException or httpBinding is set.

Consumer reply

null, text, bytes, stream or file

The response body: text, bytes, a stream or a file. A Map, a List or a POJO is sent as an empty body (as its toString with chunked=false): marshal it first.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

OAuth Bearer token validation

Servlet consumers can validate incoming Authorization: Bearer tokens by setting the oauthProfile endpoint option. The profile is resolved through Camel’s OAuthTokenValidationFactory SPI. The camel-oauth component provides the default implementation for standalone Camel applications; see its documentation for validation profile options and production hardening (expected issuer and audience, HTTPS for JWKS, OIDC discovery, and introspection endpoints). Runtimes can also provide their own implementation.

If oauthProfile is set but no OAuthTokenValidationFactory is available, the route fails to start. Add camel-oauth for the default provider or include a runtime-specific provider from the platform integration.

  • Java

  • XML

  • YAML

from("servlet:secure?oauthProfile=myprofile")
    .to("direct:businessLogic");
<route>
  <from uri="servlet:secure?oauthProfile=myprofile"/>
  <to uri="direct:businessLogic"/>
</route>
- route:
    from:
      uri: servlet:secure
      parameters:
        oauthProfile: myprofile
      steps:
        - to:
            uri: direct:businessLogic

When oauthProfile is set, static profile configuration is resolved and validated at route startup. Updates to OAuth profile properties require restarting the route or Camel context before they take effect. Requests without a Bearer token or with an invalid token are rejected with HTTP 401 before the route is processed; missing credentials receive a WWW-Authenticate: Bearer response header and invalid tokens receive WWW-Authenticate: Bearer error="invalid_token". Malformed Authorization headers are rejected with HTTP 400 and WWW-Authenticate: Bearer error="invalid_request". Token validation infrastructure failures are rejected with HTTP 503. For valid tokens, the token validation result is stored on the exchange as the CamelOAuthTokenValidationResult exchange property. The raw Authorization header is removed from the Camel message before the route is invoked.

Automatic OPTIONS handling runs before OAuth validation when optionsEnabled=false, so unauthenticated CORS preflight and Allow requests keep the existing servlet behavior. If an OPTIONS route is explicitly enabled, that route is protected by OAuth like other methods.

This is Camel endpoint-level validation and does not replace servlet container security, filters, or runtime-specific authentication mechanisms. If route code accesses the native servlet request object directly, the container request still reflects the original inbound HTTP headers. If the servlet container or framework already authenticates requests, it may consume or transform the Authorization header before Camel sees it. In that case, prefer the container or framework security and do not set oauthProfile for the same path, to avoid double validation or missing-header failures; oauthProfile is intended for deployments where the container performs no authentication.

Message Headers

Camel will apply the same Message Headers as the HTTP component.

Camel will also populate all request.parameter and request.headers. For example, if a client request has the URL, http://myserver/myserver?orderid=123, the exchange will contain a header named orderid with the value 123.

Examples

You can consume only from endpoints generated by the Servlet component. Therefore, it should be used only as input into your Camel routes. To issue HTTP requests against other HTTP endpoints, use the HTTP Component.

Example CamelHttpTransportServlet configuration

Camel Spring Boot / Camel Quarkus

When running camel-servlet on the Spring Boot or Camel Quarkus runtimes, CamelHttpTransportServlet is configured for you automatically and is driven by configuration properties. Refer to the camel-servlet configuration documentation for these runtimes.

Servlet container / application server

If you’re running Camel standalone on a Servlet container or application server, you can use web.xml to configure CamelHttpTransportServlet.

For example, to define a route that exposes an HTTP service under the path /services.

XML-only: web.xml servlet configuration
<web-app>
  <servlet>
    <servlet-name>CamelServlet</servlet-name>
    <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CamelServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
</web-app>

Example route

  • Java

  • XML

  • YAML

from("servlet:hello")
    .setBody(simple("<b>Got Content-Type: ${header.Content-Type}, URI: ${header.CamelHttpUri}</b>"));
<route>
  <from uri="servlet:hello"/>
  <setBody>
    <simple>&lt;b&gt;Got Content-Type: ${header.Content-Type}, URI: ${header.CamelHttpUri}&lt;/b&gt;</simple>
  </setBody>
</route>
- route:
    from:
      uri: servlet:hello
      steps:
        - setBody:
            simple: "<b>Got Content-Type: ${header.Content-Type}, URI: ${header.CamelHttpUri}</b>"

Camel Servlet HTTP endpoint path

The full path where the camel-servlet HTTP endpoint is published depends on:

  • The Servlet application context path

  • The configured Servlet mapping URL patterns

  • The camel-servlet endpoint URI context path

For example, if the application context path is /camel and CamelHttpTransportServlet is configured with a URL mapping of /services/*. Then a Camel route like from("servlet:hello") would be published to a path like http://localhost:8080/camel/services/hello.

Rest DSL

The Rest DSL consumers of the servlet component use the endpoint options set with restConfiguration().endpointProperty(…​), or as component options, such as attachmentMultipartBinding and mapHttpMessageBody. A custom httpBinding set with endpointProperty("httpBinding", "#myBinding") is used as it is. A custom httpBinding set on the component is used only when it extends org.apache.camel.component.servlet.ServletRestHttpBinding, which maps the path placeholders such as {id} to headers.

Servlet asynchronous support

To enable Camel to benefit from Servlet asynchronous support, you must enable the async boolean init parameter by setting it to true.

By default, the servlet thread pool is used for exchange processing. However, to use a custom thread pool, you can configure an init parameter named executorRef with the String value set to the name of a bean bound to the Camel registry of type Executor. If no bean was found in the Camel registry, the Servlet component will attempt to fall back on an executor policy or default executor service.

If you want to force exchange processing to wait in another container background thread, you can set the forceAwait boolean init parameter to true.

On the Camel Quarkus runtime, these init parameters can be set via configuration properties. Refer to the Camel Quarkus Servlet extension documentation for more information.

On other runtimes you can configure these parameters in web.xml as follows.

XML-only: web.xml with async servlet init parameters
<web-app>
    <servlet>
        <servlet-name>CamelServlet</servlet-name>
        <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
        <init-param>
            <param-name>async</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>executorRef</param-name>
            <param-value>my-custom-thread-pool</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>CamelServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

Camel JARs on an application server boot classpath

If deploying into an application server / servlet container and you choose to have Camel JARs such as camel-core, camel-servlet, etc on the boot classpath. Then the servlet mapping list will be shared between multiple deployed Camel application in the app server.

Having Camel JARs on the boot classpath of the application server is not best practice.

In this scenario, you must define a custom and unique servlet name in each of your Camel applications. For example, in web.xml:

XML-only: web.xml with custom servlet name
<web-app>
    <servlet>
      <servlet-name>MyServlet</servlet-name>
      <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
      <servlet-name>MyServlet</servlet-name>
      <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

In your Camel servlet endpoints, include the servlet name:

  • Java

  • XML

  • YAML

from("servlet://foo?servletName=MyServlet")
<route>
  <from uri="servlet://foo?servletName=MyServlet"/>
  <!-- ... -->
</route>
- route:
    from:
      uri: servlet://foo
      parameters:
        servletName: MyServlet
      steps:
        - to:
            uri: direct:businessLogic

Camel detects duplicate Servlet names and will fail to start the application. You can control and ignore such duplicates by setting the servlet init parameter ignoreDuplicateServletName to true as follows:

XML-only: web.xml init parameter to ignore duplicate servlet names
  <servlet>
    <servlet-name>CamelServlet</servlet-name>
    <display-name>Camel Http Transport Servlet</display-name>
    <servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
    <init-param>
      <param-name>ignoreDuplicateServletName</param-name>
      <param-value>true</param-value>
    </init-param>
  </servlet>

But it is strongly advised to use unique servlet-name for each Camel application to avoid this duplication clash, as well any unforeseen side effects.