Archive for March, 2017


setup maria db jdbc resources in tomcat 9

This page describes how to setup Maria DB JDBC Resources in Tomcat 9 and how to create a servlet based webapp without a web.xml.

Full downloadable source for this page is available here. Corrections and enhancements are welcome, fork, change and push back to GitHub.

Database Drivers

Place the database driver jar file into the server/lib folder.

Define the resource in Tomcat

Place the following into the $CATALINA_BASE/conf/context.xml

  <Resource name="jdbc/batch" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="username" password="password" driverClassName="org.mariadb.jdbc.Driver"

Please note that if you are running in Eclipse and have Tomcat setup as a WTP project then this file is located in the “Server” project in your eclipse workspace.

Test using Snoop JSP

To test the datasource simply create a snoop jsp to perform a lookup.

Test using your own Servlet


package com.test;

import java.sql.Connection;
import java.sql.DatabaseMetaData;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet(urlPatterns = "/testServlet", loadOnStartup = 1)
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// You may use the following lines to initialize the context.
		// Obtain our environment naming context
		Context initCtx;
		try {
			initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");

			// A data source can be obtained by doing the following.
			// Look up our data source
			DataSource ds = (DataSource) envCtx.lookup("jdbc/test");

			// Allocate and use a connection from the pool
			// ... use this connection to access the database ...
			try (PrintWriter writer = resp.getWriter(); Connection conn = ds.getConnection();) {
				writer.println("connected: " + !conn.isClosed());
				DatabaseMetaData metadata = conn.getMetaData();
				writer.println("Database Product Name: " + metadata.getDatabaseProductName());
				writer.println("Database Product Version: " + metadata.getDatabaseProductVersion());
				writer.println("Logged User: " + metadata.getUserName());
				writer.println("JDBC Driver: " + metadata.getDriverName());
				writer.println("Driver Version: " + metadata.getDriverVersion());
		} catch (Exception e) {

If you are using the popular spring framework you can do the following

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/test"/>
    <property name="resourceRef" value="true"/>

Restart and visit http://localhost:8080/test-jndi/testServlet to view the results of the connection.

Full downloadable source for this page is available here.

JNDI lookup for a datasource in JBOSS

This page describes how to perform a jndi lookup in JBoss EAP 7. In the past the lookup string was always a confusing mess. Do we use “java/jdbc/dsName” or “java:comp/env” etc… With JBoss EAP 7 its simplified.

If you have a datasource defined in jboss as: java:/test


                <datasource jta="true" jndi-name="java:/test" pool-name="Test" enabled="true" use-ccm="true">

Getting the datasource is as simple as writing the following anywhere in your application.

	public DataSource getDataSource() throws Exception {
		return (DataSource) (new InitialContext()).lookup("test");

Setting up a datasource in JBOSS EAP 7

Go to {JBOSS_HOME}\modules.
Create following directory structure.
JBOSS_HOME}\modules\com\oracle\ojdbc6\main (the “main” as last folder is crucial!)
In that folder put the oracle jdbc jar. For example ojdbc6-
In the same folder create a file module.xml
Add this content to the file:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="">
 <resource-root path="ojdbc6-"/>
 <module name="javax.api"/>
 <module name="javax.transaction.api"/>
 <module name="javax.servlet.api" optional="true"/>


                    <driver name="mariadb" module="org.mariadb"/>

Using the admin UI add the datasource. The driver should appear in the list of available drivers on the system.


JAX-RS Spring based project example

The following page describes how to get a spring context initialized and injected into a rest based project running on JBOSS AS.

Technology Stack

  • JAX-RS
  • Spring
Full downloadable source for this page is available here. Corrections and enhancements are welcome, fork, change and push back to GitHub.

Maven Project Configuration


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">


        <!-- other plug-in versions -->

        <!-- maven-compiler-plugin -->

            <!-- Define the version of the JBoss Java EE APIs we want to import.
                Any dependencies from org.jboss.spec will have their version defined by this
                BOM -->
            <!-- JBoss distributes a complete set of Java EE APIs including
                a Bill of Materials (BOM). A BOM specifies the versions of a "stack" (or
                a collection) of artifacts. We use this here so that we always get the correct
                versions of artifacts. Here we use the jboss-javaee-7.0 stack (you can
                read this as the JBoss stack of the Java EE APIs). You can actually
                use this stack with any version of JBoss EAP that implements Java EE. -->


        <!-- Import the CDI API, we use provided scope as the API is included in JBoss EAP -->

        <!-- Import the Common Annotations API (JSR-250), we use provided scope
            as the API is included in JBoss EAP -->

        <!-- Import the JAX-RS API, we use provided scope as the API is included in JBoss EAP -->
<!-- Spring -->        

        <!-- Set the name of the WAR, used as the context root when the app
            is deployed -->
               <!-- Java EE doesn't require web.xml, Maven needs to catch up! -->

Web Configuration and Html files


<web-app version="3.1" xmlns=""
    <!-- One of the way of activating REST Servises is adding these lines, the server is responsible for adding the corresponding servlet automatically. If the src folder, class has the Annotations to receive REST invocation-->


<?xml version="1.0" encoding="UTF-8"?>
<!-- Marker file indicating CDI should be enabled -->
<beans xmlns="" xmlns:xsi=""


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <p>Choose between <em>JSON</em> or <em>XML</em>:

    	<li><a href="rest/json">JSON</a></li>
        <li><a href="rest/xml">XML</a></li>

Java Code

Here we have a spring config via java annotated class.


package com.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

 * This class replaces the spring xml configuration.
public class SpringConfig {


Next we have a context holder class. This is a CDI Bean that will hold a reference to a spring context. This is the only place CDI is used in the project.

package com.test;

import java.util.Arrays;

import javax.annotation.PostConstruct;
import javax.inject.Singleton;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

 * A simple CDI service which is able to say hello to someone
public class ContextHolder {

	private AnnotationConfigApplicationContext ctx = null;
	void postConstruct() {
        // Initialize the spring framework.
        ctx = new AnnotationConfigApplicationContext();  
		System.out.println("Post construct on service called.");
	public ApplicationContext getContext() {
		return ctx;


Spring Service Bean

package com.test;

import org.springframework.stereotype.Service;

public class HelloService {
    String createHelloMessage(String name) {
        return "Hello " + name + "!";

Rest Resource

package com.test;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

 * A simple REST service which is able to say hello to someone using HelloService Please take a look at the web.xml where JAX-RS
 * is enabled

public class HelloWorld {
    private ContextHolder contextHolder;
    private HelloService helloService;

    void postConstruct() {
    	System.out.println("PostConstruct called.");
    	helloService = (HelloService) contextHolder.getContext().getBean("helloService");
    @Produces({ "application/json" })
    public String getHelloWorldJSON() {
        return "{\"result\":\"" + helloService.createHelloMessage("World") + "\"}";

    @Produces({ "application/xml" })
    public String getHelloWorldXML() {
        return "<xml><result>" + helloService.createHelloMessage("World") + "</result></xml>";

Full downloadable source for this page is available here.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 75 other followers

March 2017
« Mar    

Blog Stats

  • 807,300 hits