Helllllooooooo World example with..

..JSF and Tomcat and Jetty and JPA and Hibernate and H2DB and Maven and Twitter Bootstrap and and and..

We need some color on this page, so here is a green header..

So just another day, me minding my own business as usual..

I start h2db as seen below from command line:

And as seen below, I can easily login to the server, just play with it etc..

And this is the directory layout I have:

And lets show the code as well, starting with pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>biz.tugay</groupId>
    <artifactId>studentform</artifactId>
    <packaging>war</packaging>
 
    <version>1.0-SNAPSHOT</version>
 
    <name>studentform Maven Webapp</name>
    <url>http://www.tugay.biz</url>
 
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- JSTL is implemented by JSF, sort of,
        but the Interfaces are required in classpath -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.13</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.13</version>
        </dependency>
 
        <!-- Persistency Dependencies -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
 
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.192</version>
        </dependency>
    </dependencies>
 
    <build>
        <finalName>studentform</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.1.v20140609</version>
            </plugin>
        </plugins>
    </build>
 
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
</project>

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
 
    <persistence-unit name="jdbc/studentform" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <non-jta-data-source>java:comp/env/jdbc/studentform</non-jta-data-source>
        <properties>
            <property name="connection.useUnicode" value="true"/>
            <property name="connection.characterEncoding" value="utf-8"/>
        </properties>
    </persistence-unit>
 
</persistence>

Student.java
package biz.tugay.db;
 
import javax.persistence.*;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 7/28/2016
 * Time: 10:37 PM
 */
 
@Entity
@Table(name = "STUDENT")
public class Student {
    private String id;
    private String fullname;
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    @Basic
    @Column(name = "FULLNAME")
    public String getFullname() {
        return fullname;
    }
 
    public void setFullname(String fullname) {
        this.fullname = fullname;
    }
}

BaseDao.java
package biz.tugay.db;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 7/28/2016
 * Time: 10:48 PM
 */
public class BaseDao {
    private static EntityManagerFactory entityManagerFactory;
 
    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("jdbc/studentform");
    }
 
    public static EntityManager getEntityManager() {
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager;
    }
}

StudentDao.java
package biz.tugay.db;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import java.util.List;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 7/28/2016
 * Time: 10:46 PM
 */
public class StudentDao {
    public static List<Student> getAllStudents() {
        final EntityManager em = BaseDao.getEntityManager();
        final String sqlQuery = "Select student from Student student";
        final TypedQuery<Student> query
                = em.createQuery(sqlQuery, Student.class);
        final List<Student> allStudents = query.getResultList();
        em.close();
        return allStudents;
    }
 
    public static void persistStudent(Student student) {
        final EntityManager em = BaseDao.getEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        transaction.begin();
        em.merge(student);
        transaction.commit();
        em.close();
    }
}

web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
 
    <servlet>
        <servlet-name>FacesServlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>FacesServlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
 
    <context-param>
        <param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
        <param-value>true</param-value>
    </context-param>
 
    <context-param>
        <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
        <param-value>true</param-value>
    </context-param>
 
    <context-param>
        <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
        <param-value>true</param-value>
    </context-param>
 
    <filter>
        <filter-name>requestEncodingFilterer</filter-name>
        <filter-class>biz.tugay.filter.RequestEncodingFilter</filter-class>
    </filter>
 
    <filter-mapping>
        <filter-name>requestEncodingFilterer</filter-name>
        <servlet-name>FacesServlet</servlet-name>
    </filter-mapping>
 
    <welcome-file-list>
        <welcome-file>studentform.xhtml</welcome-file>
    </welcome-file-list>
 
</web-app>

context.xml
<?xml version='1.0' encoding='utf-8'?>
<Context>
    <Resource name="jdbc/studentform" auth="Container" type="javax.sql.DataSource"
              maxActive="5" maxIdle="5" maxWait="10000"
              username="sa" password="" driverClassName="org.h2.Driver"
              url="jdbc:h2:tcp://localhost:9092/~/h2dbs/studentform"/>
</Context>

studentform.xhtml
<!--
    User: Koray Tugay (koray@tugay.biz)
    Date: 7/22/2016
    Time: 7:58 PM
-->
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<f:view>
    <h:head>
        <title>Registiration Form</title>
        <h:outputStylesheet library="css" name="bootstrap.min.css"/>
    </h:head>
    <h:body>
        <h:panelGroup layout="block"
                      styleClass="container"
                      style="margin: 100px 15px 15px 200px;">
            <h:form id="studentRegistirationForm"
                    accept-charset="utf-8"
                    prependId="false">
                <fieldset>
                    <legend><h:outputText value="Student Form Example"/></legend>
                    <h:outputLabel id="fullnameLabel"
                                   for="fullname"
                                   value="Name:"/>
                    <h:inputText id="fullname"
                                 styleClass="input input-xlarge"
                                 value="#{studentFormBean.fullname}">
                    </h:inputText>
                    <br/>
                    <h:commandButton id="submitFormButton"
                                     styleClass="btn"
                                     value="Submit Form"
                                     action="#{studentFormBean.registerStudent()}"/>
                </fieldset>
            </h:form>
            <br/>
            <h:panelGroup layout="block" styleClass="well well-large">
                <c:forEach items="#{studentFormBean.allStudents()}" var="student">
                    <h:outputText value="#{student.getFullname()}"/>
                    <br/>
                </c:forEach>
            </h:panelGroup>
        </h:panelGroup>
        <h:outputScript library="js" name="jquery.js"></h:outputScript>
        <h:outputScript library="js" name="bootstrap.min.js"></h:outputScript>
    </h:body>
</f:view>
</html>

StudentFormBean.java
package biz.tugay.backingbeans;
 
import biz.tugay.db.Student;
import biz.tugay.db.StudentDao;
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.List;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 7/23/2016
 * Time: 10:14 AM
 */
 
@ManagedBean
@SessionScoped
public class StudentFormBean {
 
    private String fullname;
 
    public String getFullname() {
        return fullname;
    }
 
    public void setFullname(String fullname) {
        this.fullname = fullname;
    }
 
    public String registerStudent() {
        final Student student = new Student();
        student.setFullname(fullname);
        StudentDao.persistStudent(student);
        return "studentform?faces-redirect=true";
    }
 
    public List<Student> allStudents() {
        return StudentDao.getAllStudents();
    }
}

Ok so, lets build our application..

copy the war file to webapps directory..

and start Tomcat..

Lets test our application:


Ok, so everything looks fine..

Now lets stop Tomcat, and simply try with jetty plugin..
Caused by:
javax.naming.NameNotFoundException; remaining name 'jdbc/studentform'
 at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:538)
 at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:569)
 at org.eclipse.jetty.jndi.NamingContext.lookup(NamingContext.java:569)
 at org.eclipse.jetty.jndi.java.javaRootURLContext.lookup(javaRootURLContext.java:101)
 at javax.naming.InitialContext.lookup(InitialContext.java:415)
 at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:114)

Why am I not surprised...

Anyway, to make it work with Jetty, I needed these, in pom.xml I needed this dependency:
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>

and in WEB-INF folder, I needed to create a file called: jetty-env.xml
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
 
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <New id="h2db" class="org.eclipse.jetty.plus.jndi.Resource">
        <Arg><Ref id="thisfile"/></Arg>
        <Arg>jdbc/studentform</Arg>
        <Arg>
            <New class="org.apache.commons.dbcp.BasicDataSource">
                <Set name="driverClassName">org.h2.Driver</Set>
                <Set name="url">jdbc:h2:tcp://localhost:9092/~/h2dbs/studentform</Set>
                <Set name="username">sa</Set>
                <Set name="password"></Set>
                <Set name="maxActive">50</Set>
            </New>
        </Arg>
    </New>
</Configure>

and in web.xml I needed this:
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/studentform</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

..and application will work with jetty plugin as well!!!

Well this took me some time to figure out, but I really like the h2 db, for now at least.. It is pretty easy to use.

Also thanks to: http://blog.max.berger.name/2010/04/datasource-in-jetty-through-jndi.html