Using a servlet config file with a CXF JAX-RS web-service

I spent some time searching for how to do this, so thought I’d share my findings.

Problem:

I created an Apache CXF JAX-RS web-service using the Maven2 archetype “cxf-jaxrs-service (Simple CXF JAX-RS webapp service using Spring configuration)”. Using this as a boiler-plate, I then created my own RESTful web-service endpoint.

The problem was, without having my class extend HttpServlet, how would I get a hold of configuration parameters specified in a servlet configuration file? For example, within Tomcat’s META-INF/context.xml?

Solution:

It’s as simple as just utilizing the @Servlet context variable.

First, ensure you have the following Maven dependency included in your project’s pom.xml:


<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>2.4</version>

<scope>provided</scope>

</dependency>

Second, define a variable within your REST resource class as such:


@Context private ServletContext context;

Finally, read parameters from the context variable via:


context.getInitParameter("MyParameterName");

That’s it!

Advertisements

One thought on “Using a servlet config file with a CXF JAX-RS web-service

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s