Skip to content

Simple Web Application Setup

sclassen edited this page Jan 11, 2013 · 2 revisions

java code

public class BootstrapServletListener extends GuiceServletContextListener {
    protected Injector getInjector() {
        final PersistenceModule persistenceModule = new PersistenceModule();
        persistenceModule.addContainerManagedPersistenceUnit("java:comp/env/foobar/puJndiName").useResourceLocalTransaction();

        final ServletModule servletModule = new ServletModule() {
            filter("/*").through(PersistenceFilter.class);
        };

        return Guice.createInjector(servletModule, persistenceModule, getApplicationSpecificModules());
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>FooBar App</display-name>
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.foo.bar.BootstrapServletListener</listener-class>
    </listener>
    <!-- More config. -->
</web-app>

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
    <persistence-unit name="puName" transaction-type="RESOURCE_LOCAL">
        <!-- your configuration -->
    </peristence-unit>
</peristence>

JNDI Binding

In order to allow container managed persistence units the persistence unit must be bound in the JNDI framework.

If your container follows the J2EE Standard 5.0 add the following to your web.xml

<peristence-unit-ref>
    <peristence-unit-ref-name>foobar/puJndiName</peristence-unit-ref-name>
    <peristence-unit-name>puName</peristence-unit-name>
</peristence-unit-ref>

JBoss AS7.0 and 7.1 do not support placing the JNDI binding in the web.xml. Instead add the following to your persistence.xml

<property name="jboss.entity.manager.factory.jndi.name" value="java:comp/env/foobar/puJndiName" />
<property name="jboss.as.jpa.managed" value="true" />

Structure of the .war

+ app.war
|    + META-INF
|    |    + MANIFEST.MF
|    |    + persistence.xml
|    + WEB-INF
|    |    + classes
|    |    |    + META-INF
|    |    |    |    + MANIFEST.MF
|    |    |    + foo
|    |    |    |    + bar
|    |    |    |    |    + BootstrapServletListener.class
|    |    + lib
|    |    |    + guice.jar
|    |    |    + guice-jpa.jar.