Software Development

Tomcat 8 and Java EE CDI

This post demonstrates how Dependency Injection works with JavaEE CDI and Tomcat 8. We’ll display some text from a bean injected into our Servlet via CDI.

As we know, Tomcat is just a Servlet Container and does not have other JavaEE components available out-of-the-box. Tomee may be a better alternative but should we go all-out “Enterprise”,  choose a JavaEE-compliant Application Server like JBoss WildFly or IBM Websphere.

Requirements

Stuff used in this post.

  • Eclipse Mars.2 Release (4.5.2)
  • Java 8
  • Windows 10 64bit
  • Tomcat 8.0.39
  • Maven 3.3.3 (Embedded in Eclipse)

Key Maven Dependencies

These are the key dependencies.

javaee-web-api

[wp_ad_camp_4]

This contains most API related to Web Applications.

cdi-api

This is the CDI API.

weld-servlet

A reference implementation of CDI on a Servlet Container.

[wp_ad_camp_3]

CDI Bean

This bean is created in the CDI “container” and injected into our Servlet. We used @ApplicationScoped and the bean is available until Tomcat/Web Application is shutdown.

Our Servlet

[wp_ad_camp_2]

Configuration and other XML files

There are other configurations that are needed before we could run and test our simple web application.

Define beans.xml

This file contains the following and should be placed in "Deployed Resources"/webapp/WEB-INF.

Define web.xml

[wp_ad_camp_1]

Same with beans.xml, this files should be placed "Deployed Resources"/webapp/WEB-INF.

Define context.xml

This file should be placed under "Deployed Resources"/web-resources/META-INF.

Testing

The web application is launched from Eclipse.

Our servlet outputs this page.

[wp_ad_camp_5]

Download the codes

https://github.com/Turreta/Tomcat-8-and-Java-EE-CDI

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like