Chapter 279. Servlet Component


Available as of Camel version 2.0

The servlet: component provides HTTP based endpoints for consuming HTTP requests that arrive at a 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>

INFO: Stream. Servlet is stream based, which means the input it receives is submitted to Camel as a stream. That means 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.

279.1. URI format

servlet://relative_path[?options]

You can append query options to the URI in the following format, ?option=value&option=value&…​

279.2. Options

The Servlet component supports 8 options which are listed below.

NameDescriptionDefaultType

servletName (consumer)

Default name of servlet to use. The default name is CamelServlet.

 

String

httpRegistry (consumer)

To use a custom org.apache.camel.component.servlet.HttpRegistry.

 

HttpRegistry

attachmentMultipart Binding (consumer)

Whether to automatic bind multipart/form-data as attachments on the Camel Exchange. The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together. Remove disableStreamCache to use AttachmentMultipartBinding. This is turn off by default as this may require servlet specific configuration to enable this when using Servlet’s.

false

boolean

httpBinding (advanced)

To use a custom HttpBinding to control the mapping between Camel message and HttpClient.

 

HttpBinding

httpConfiguration (advanced)

To use the shared HttpConfiguration as base configuration.

 

HttpConfiguration

allowJavaSerialized Object (advanced)

Whether to allow java serialization when a request uses context-type=application/x-java-serialized-object. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

headerFilterStrategy (filter)

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

 

HeaderFilterStrategy

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Servlet endpoint is configured using URI syntax:

servlet:contextPath

with the following path and query parameters:

279.2.1. Path Parameters (1 parameters):

NameDescriptionDefaultType

contextPath

Required The context-path to use

 

String

279.2.2. Query Parameters (21 parameters):

NameDescriptionDefaultType

disableStreamCache (common)

Determines whether or not the raw input stream from Servlet is cached or not (Camel will read the stream into a in memory/overflow to file, Stream caching) cache. By default Camel will cache the Servlet input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. DefaultHttpBinding will copy the request input stream into a stream cache and put it into message body if this option is false to support reading the stream multiple times. If you use Servlet to bridge/proxy an endpoint then consider enabling this option to improve performance, in case you do not need to read the message payload multiple times. The http/http4 producer will by default cache the response body stream. If setting this option to true, then the producers will not cache the response body stream but use the response stream as-is as the message body.

false

boolean

headerFilterStrategy (common)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

 

HeaderFilterStrategy

httpBinding (common)

To use a custom HttpBinding to control the mapping between Camel message and HttpClient.

 

HttpBinding

async (consumer)

Configure the consumer to work in async mode

false

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

chunked (consumer)

If this option is false the Servlet will disable the HTTP streaming and set the content-length header on the response

true

boolean

httpMethodRestrict (consumer)

Used to only allow consuming if the HttpMethod matches, such as GET/POST/PUT etc. Multiple methods can be specified separated by comma.

 

String

matchOnUriPrefix (consumer)

Whether or not the consumer should try to find a target consumer by matching the URI prefix if no exact match is found.

false

boolean

responseBufferSize (consumer)

To use a custom buffer size on the javax.servlet.ServletResponse.

 

Integer

servletName (consumer)

Name of the servlet to use

CamelServlet

String

transferException (consumer)

If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

attachmentMultipartBinding (consumer)

Whether to automatic bind multipart/form-data as attachments on the Camel Exchange. The options attachmentMultipartBinding=true and disableStreamCache=false cannot work together. Remove disableStreamCache to use AttachmentMultipartBinding. This is turn off by default as this may require servlet specific configuration to enable this when using Servlet’s.

false

boolean

eagerCheckContentAvailable (consumer)

Whether to eager check whether the HTTP requests has content if the content-length header is 0 or not present. This can be turned on in case HTTP clients do not send streamed data.

false

boolean

exceptionHandler (consumer)

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options 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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

optionsEnabled (consumer)

Specifies whether to enable HTTP OPTIONS for this Servlet consumer. By default OPTIONS is turned off.

false

boolean

traceEnabled (consumer)

Specifies whether to enable HTTP TRACE for this Servlet consumer. By default TRACE is turned off.

false

boolean

mapHttpMessageBody (advanced)

If this option is true then IN exchange Body of the exchange will be mapped to HTTP body. Setting this to false will avoid the HTTP mapping.

true

boolean

mapHttpMessageFormUrl EncodedBody (advanced)

If this option is true then IN exchange Form Encoded body of the exchange will be mapped to HTTP. Setting this to false will avoid the HTTP Form Encoded body mapping.

true

boolean

mapHttpMessageHeaders (advanced)

If this option is true then IN exchange Headers of the exchange will be mapped to HTTP headers. Setting this to false will avoid the HTTP Headers mapping.

true

boolean

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

279.3. 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.

279.4. Usage

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

279.5. Putting Camel JARs in the app server boot classpath

If you put the Camel JARs such as camel-core, camel-servlet, etc. in the boot classpath of your application server (eg usually in its lib directory), then mind that the servlet mapping list is now shared between multiple deployed Camel application in the app server.

Mind that putting Camel JARs in the boot classpath of the application server is generally not best practice!

So in those situations you must define a custom and unique servlet name in each of your Camel application, eg in the web.xml define:

<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>

And in your Camel endpoints then include the servlet name as well

<route>
  <from uri="servlet://foo?servletName=MyServlet"/>
  ...
</route>

From Camel 2.11 onwards Camel will detect this duplicate and fail to start the application. You can control to ignore this duplicate 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 its strongly advised to use unique servlet-name for each Camel application to avoid this duplication clash, as well any unforeseen side-effects.

279.6. Sample

INFO: From Camel 2.7 onwards it’s easier to use Servlet in Spring web applications. See Servlet Tomcat Example for details.

In this sample, we define a route that exposes a HTTP service at http://localhost:8080/camel/services/hello.
First, you need to publish the CamelHttpTransportServlet through the normal Web Container, or OSGi Service.
Use the Web.xml file to publish the CamelHttpTransportServlet as follows:

Then you can define your route as follows:

Note

Specify the relative path for camel-servlet endpoint Since we are binding the Http transport with a published servlet, and we don’t know the servlet’s application context path, the camel-servlet endpoint uses the relative path to specify the endpoint’s URL. A client can access the camel-servlet endpoint through the servlet publish address: ("http://localhost:8080/camel/services") + RELATIVE_PATH("/hello").

279.6.1. Sample when using Spring 3.x

See Servlet Tomcat Example

279.6.2. Sample when using Spring 2.x

When using the Servlet component in a Camel/Spring application it’s often required to load the Spring ApplicationContext after the Servlet component has started. This can be accomplished by using Spring’s ContextLoaderServlet instead of ContextLoaderListener. In that case you’ll need to start ContextLoaderServlet after CamelHttpTransportServlet like this:

<web-app>
  <servlet>
        <servlet-name>CamelServlet</servlet-name>
        <servlet-class>
            org.apache.camel.component.servlet.CamelHttpTransportServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
        <servlet-name>SpringApplicationContext</servlet-name>
        <servlet-class>
            org.springframework.web.context.ContextLoaderServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
  </servlet>
<web-app>

279.6.3. Sample when using OSGi

From Camel 2.6.0, you can publish the CamelHttpTransportServlet as an OSGi service with help of SpringDM like this.

Then use this service in your camel route like this:

For versions prior to Camel 2.6 you can use an Activator to publish the CamelHttpTransportServlet on the OSGi platform

279.6.4. Usage with Spring-Boot

From Camel 2.19.0 onwards, the camel-servlet-starter library binds automatically all the rest endpoints under the "/camel/*" context path. The following table summarizes the additional configuration properties available in the camel-servlet-starter library. The automatic mapping of the Camel servlet can also be disabled.

Spring-Boot PropertyDefaultDescription

camel.component.servlet.mapping.enabled

true

Enables the automatic mapping of the servlet component into the Spring web context

camel.component.servlet.mapping.context-path

/camel/*

Context path used by the servlet component for automatic mapping

camel.component.servlet.mapping.servlet-name

CamelServlet

The name of the Camel servlet

279.7. See Also

279.8. ServletListener Component

Available as of Camel 2.11

This component is used for bootstrapping Camel applications in web applications. For example beforehand people would have to find their own way of bootstrapping Camel, or rely on 3rd party frameworks such as Spring to do it.

Note

Sidebar This component supports Servlet 2.x onwards, which mean it works also in older web containers; which is the goal of this component. Though Servlet 2.x requires to use a web.xml file as configuration. For Servlet 3.x containers you can use annotation driven configuration to boostrap Camel using the @WebListener, and implement your own class, where you boostrap Camel. Doing this still puts the challenge how to let end users easily configure Camel, which you get for free with the old school web.xml file.

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

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

279.8.1. Using

You would need to chose one of the following implementations of the abstract class org.apache.camel.component.servletlistener.CamelServletContextListener.

  • JndiCamelServletContextListener which uses the JndiRegistry to leverage JNDI for its registry.
  • SimpleCamelServletContextListener which uses the SimpleRegistry to leverage a java.util.Map as its registry.

To use this you need to configure the org.apache.camel.component.servletlistener.CamelServletContextListener in the WEB-INF/web.xml file as shown below:

279.8.2. Options

The org.apache.camel.component.servletlistener.CamelServletContextListener supports the following options which can be configured as context-param in the web.xml file.

OptionTypeDescription

propertyPlaceholder.XXX

 

To configure property placeholders in Camel. You should prefix the option with "propertyPlaceholder.", for example to configure the location, use propertyPlaceholder.location as name. You can configure all the options from the Properties component.

jmx.XXX

 

To configure JMX. You should prefix the option with "jmx.", for example to disable JMX, use jmx.disabled as name. You can configure all the options from org.apache.camel.spi.ManagementAgent. As well the options mentioned on the JMX page.

name

String

To configure the name of the CamelContext.

messageHistory

Boolean

Camel 2.12.2: Whether to enable or disable Message History (enabled by default).

streamCache

Boolean

Whether to enable Stream caching.

trace

Boolean

Whether to enable Tracer.

delayer

Long

To set a delay value for Delay Interceptor.

handleFault

Boolean

Whether to enable handle fault.

errorHandlerRef

String

Refers to a context scoped Error Handler to be used.

autoStartup

Boolean

Whether to start all routes when starting Camel.

useMDCLogging

Boolean

Whether to use MDC logging.

useBreadcrumb

Boolean

Whether to use breadcrumb.

managementNamePattern

String

To set a custom naming pattern for JMX MBeans.

threadNamePattern

String

To set a custom naming pattern for threads.

properties.XXX

 

To set custom properties on CamelContext.getProperties. This is seldom in use.

routebuilder.XXX

 

To configure routes to be used. See below for more details.

CamelContextLifecycle

 

Refers to a FQN classname of an implementation of org.apache.camel.component.servletlistener.CamelContextLifecycle. Which allows to execute custom code before and after CamelContext has been started or stopped. See below for further details.

XXX

 

To set any option on CamelContext.

279.8.3. Examples

See Servlet Tomcat No Spring Example.

279.8.4. Accessing the created CamelContext

Available as of Camel 2.14/2.13.3/2.12.5

The created CamelContext is stored on the ServletContext as an attribute with the key "CamelContext". You can get hold of the CamelContext if you can get hold of the ServletContext as shown below:

ServletContext sc = ...
CamelContext camel = (CamelContext) sc.getAttribute("CamelContext");
 

279.8.5. Configuring routes

You need to configure which routes to use in the web.xml file. You can do this in a number of ways, though all the parameters must be prefixed with "routeBuilder".

279.8.5.1. Using a RouteBuilder class

By default Camel will assume the param-value is a FQN classname for a Camel RouteBuilder class, as shown below:

  <context-param>
    <param-name>routeBuilder-MyRoute</param-name>
    <param-value>org.apache.camel.component.servletlistener.MyRoute</param-value>
  </context-param>

You can specify multiple classes in the same param-value as shown below:

  <context-param>
    <param-name>routeBuilder-routes</param-name>
    <!-- we can define multiple values separated by comma -->
    <param-value>
      org.apache.camel.component.servletlistener.MyRoute,
      org.apache.camel.component.servletlistener.routes.BarRouteBuilder
    </param-value>
  </context-param>

The name of the parameter does not have a meaning at runtime. It just need to be unique and start with "routeBuilder". In the example above we have "routeBuilder-routes". But you could just as well have named it "routeBuilder.foo".

279.8.5.2. Using package scanning

You can also tell Camel to use package scanning, which mean it will look in the given package for all classes of RouteBuilder types and automatic adding them as Camel routes. To do that you need to prefix the value with "packagescan:" as shown below:

  <context-param>
    <param-name>routeBuilder-MyRoute</param-name>
    <!-- define the routes using package scanning by prefixing with packagescan: -->
    <param-value>packagescan:org.apache.camel.component.servletlistener.routes</param-value>
  </context-param>

279.8.5.3. Using a XML file

You can also define Camel routes using XML DSL, though as we are not using Spring or Blueprint the XML file can only contain Camel route(s).

In the web.xml you refer to the XML file which can be from "classpath", "file" or a "http" url, as shown below:

  <context-param>
    <param-name>routeBuilder-MyRoute</param-name>
    <param-value>classpath:routes/myRoutes.xml</param-value>
  </context-param>

And the XML file is:

routes/myRoutes.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- the xmlns="http://camel.apache.org/schema/spring" is needed -->
<routes xmlns="http://camel.apache.org/schema/spring">

  <route id="foo">
    <from uri="direct:foo"/>
    <to uri="mock:foo"/>
  </route>

  <route id="bar">
    <from uri="direct:bar"/>
    <to uri="mock:bar"/>
  </route>

</routes>

Notice that in the XML file the root tag is <routes> which must use the namespace "http://camel.apache.org/schema/spring". This namespace is having the spring in the name, but that is because of historical reasons, as Spring was the first and only XML DSL back in the time. At runtime no Spring JARs is needed. Maybe in Camel 3.0 the namespace can be renamed to a generic name.

279.8.5.4. Configuring propert placeholders

Here is a snippet of a web.xml configuration for setting up property placeholders to load myproperties.properties from the classpath

  <!-- setup property placeholder to load properties from classpath -->
  <!-- we do this by setting the param-name with propertyPlaceholder. as prefix and then any options such as location, cache etc -->
  <context-param>
    <param-name>propertyPlaceholder.location</param-name>
    <param-value>classpath:myproperties.properties</param-value>
  </context-param>
  <!-- for example to disable cache on properties component, you do -->
  <context-param>
    <param-name>propertyPlaceholder.cache</param-name>
    <param-value>false</param-value>
  </context-param>

279.8.5.5. Configuring JMX

Here is a snippet of a web.xml configuration for configuring JMX, such as disabling JMX.

  <!-- configure JMX by using names that is prefixed with jmx. -->
  <!-- in this example we disable JMX -->
  <context-param>
    <param-name>jmx.disabled</param-name>
    <param-value>true</param-value>
  </context-param>

JNDI or Simple as Camel Registry ^^^^^^^^^^^^^^^^^^

This component uses either JNDI or Simple as the Registry.
This allows you to lookup Beans and other services in JNDI, and as well to bind and unbind your own Beans.

This is done from Java code by implementing the org.apache.camel.component.servletlistener.CamelContextLifecycle.

279.8.5.6. Using custom CamelContextLifecycle

In the code below we use the callbacks beforeStart and afterStop to enlist our custom bean in the Simple Registry, and as well to cleanup when we stop.

Then we need to register this class in the web.xml file as shown below, using the parameter name "CamelContextLifecycle". The value must be a FQN which refers to the class implementing the org.apache.camel.component.servletlistener.CamelContextLifecycle interface.

  <context-param>
    <param-name>CamelContextLifecycle</param-name>
    <param-value>org.apache.camel.component.servletlistener.MyLifecycle</param-value>
  </context-param>

As we enlisted our HelloBean Bean using the name "myBean" we can refer to this Bean in the Camel routes as shown below:

public class MyBeanRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("seda:foo").routeId("foo")
            .to("bean:myBean")
            .to("mock:foo");
    }
}

Important: If you use org.apache.camel.component.servletlistener.JndiCamelServletContextListener then the CamelContextLifecycle must use the JndiRegistry as well. And likewise if the servlet is org.apache.camel.component.servletlistener.SimpleCamelServletContextListener then the CamelContextLifecycle must use the SimpleRegistry

279.8.6. See Also

Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.