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 |
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,*.yamlfiles, 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 |
|---|---|---|---|
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 | |
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 | |
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 | |
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 | |
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 | ||
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 | ||
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 | |
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 | |
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 | ||
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 | ||
To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | ||
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 |
|---|---|---|---|
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 |
|---|---|---|---|
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 | |
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 | |
To use a custom HeaderFilterStrategy to filter the headers that are mapped between the Camel message and the HTTP request and response. | HeaderFilterStrategy | ||
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 | ||
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 | |
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 | |
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 | ||
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 | |
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 | |
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 | |
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 | ||
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 | |
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 | |
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 | |
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 | |
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 | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
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 | ||
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 | |
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 | |
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 | |
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 | |
Whether the consumer accepts HTTP TRACE requests and routes them. When false, a TRACE request gets the 405 Method Not Allowed response. | false | boolean | |
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 |
|---|---|---|---|
| Constant: | The HTTP method of the request, such as GET or POST. | String | |
CamelServletContextPath (consumer) Constant: | The path of the endpoint that received the request (the contextPath of the endpoint URI), for example /hello for servlet:hello. | String | |
| Constant: | 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 | |
| Constant: | The query string of the request (not URL-decoded), or null when it has none. | String | |
| Constant: | The URI of the request without the query string (HttpServletRequest.getRequestURI()), from the web application context path on. | String | |
| Constant: | The URL of the request without the query string, with the scheme, host and port (HttpServletRequest.getRequestURL()). | String | |
CamelHttpCharacterEncoding (consumer) Constant: | The charset that the request declares (HttpServletRequest.getCharacterEncoding()). Set only when the request has one. | String | |
| Constant: | The Content-Type of the request. In the reply, the Content-Type of the response. | String | |
CamelHttpResponseCode (consumer) Constant: | 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 | |
| Constant: | Whether the response is written in chunked mode (Transfer-Encoding: chunked), overriding the chunked option. | Boolean | |
| Constant: | 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 |
| 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 |
Consumer reply |
| 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 |
-
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 |
| 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 |
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.
<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><b>Got Content-Type: ${header.Content-Type}, URI: ${header.CamelHttpUri}</b></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.
<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:
<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:
<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.