May 14, 2017

Tomcat JavaBean Resources Factory

Introduction

This works for Tomcat 7, 8 and 9, but here I will use Tomcat 8.

Purpose

Tomcat have DI (Dependency Injection), much the same found in Spring and Java EE, which can be used for mocking or a loose coupling architecture.

POJO

First lets write our POJO class that we want to lookup inside our application.

package se.magnuskkarlsson.example.tomcat;

public class FooBean {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

XML Configuration

Now we are ready to declare our POJO in either $APP_HOME/META-INF/context.xml (only available inside appl) or $TOMCAT_HOME/context.xml (available across all appl).

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/example-tomcat">

    ...
    <Resource name="bean/FooBean" auth="Container"
        type="se.magnuskkarlsson.example.tomcat.FooBean" factory="org.apache.naming.factory.BeanFactory"
        text="Magnus K Karlsson" />
</Context>

Application

And this how to retrieve it inside your application.

package se.magnuskkarlsson.example.tomcat;

import java.io.IOException;

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;

@WebServlet(name = "JavaBeanResourcesServlet", urlPatterns = "/bean")
public class JavaBeanResourcesServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Context ctx = new InitialContext();
            FooBean bean = (FooBean) ctx.lookup("java:/comp/env/bean/FooBean");
            resp.getWriter().println("Data from bean " + bean.getText());
        } catch (Exception e) {
            super.log("FAILED to read from bean. Cause " + e.getMessage());
            resp.getWriter().println("FAILED to read from bean. Cause " + e.getMessage());
        }
    }
}

No comments: