Standalone JPA Project Using Java SE: A Maven Way

In this post, I will show how to create a simple JPA application by using maven and Java SE JDK. All the other libraries will be taken care of by the remote repository in maven, which includes eclipselink and embedded derby db.

I will be focusing on how to use maven to generate, what project structure and programs created, how to execute the application, how to verify the database objects, and what targets can be deployed.

I hope this will help you get started, especially without using any IDEs like Eclipse, Netbean etc.

I won’t go to explain what JPA is. There are many resources and books available.

1. Generate JPA App in Seconds

Make sure to enter ’46’ as artifactID (46 is for com.github.lalyos:standalone-jpa-eclipselink-archetype) when asked in the following:

mvn archetype:generate -DgroupId=henry416 -DartifactId=test1

.................

Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 354: 46
Choose com.github.lalyos:standalone-jpa-eclipselink-archetype version: 
1: 0.0.1
2: 0.0.2
Choose a number: 2: 2
[INFO] Using property: groupId = henry416
[INFO] Using property: artifactId = test1
Define value for property 'version':  1.0-SNAPSHOT: : 
[INFO] Using property: package = henry416
Confirm properties configuration:
groupId: henry416
artifactId: test1
version: 1.0-SNAPSHOT
package: henry416
 Y: : 
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: standalone-jpa-eclipselink-archetype:0.0.2
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: henry416
[INFO] Parameter: artifactId, Value: test1
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: henry416
[INFO] Parameter: packageInPathFormat, Value: henry416
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: henry416
[INFO] Parameter: groupId, Value: henry416
[INFO] Parameter: artifactId, Value: test1
[INFO] project created from Archetype in dir: /home/henry/Test/jpatest/test1
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:42.092s
[INFO] Finished at: Thu Mar 06 21:10:38 EST 2014
[INFO] Final Memory: 10M/25M
[INFO] ------------------------------------------------------------------------

2. Project Structures Generated

henry@brimley:~/Test/jpatest/test1$ ls -ld $(find .)
drwxr-xr-x 3 henry henry 4096 2014-03-06 22:37 .
-rw-r--r-- 1 henry henry   70 2014-03-06 21:10 ./ij.properties
-rw-r--r-- 1 henry henry 1185 2014-03-06 21:10 ./pom.xml
-rwx------ 1 henry henry   60 2014-03-06 21:10 ./run.sh
-rwx------ 1 henry henry  107 2014-03-06 21:10 ./show-derby.sh
drwxr-xr-x 3 henry henry 4096 2014-03-06 21:10 ./src
drwxr-xr-x 4 henry henry 4096 2014-03-06 21:10 ./src/main
drwxr-xr-x 3 henry henry 4096 2014-03-06 21:10 ./src/main/java
drwxr-xr-x 4 henry henry 4096 2014-03-06 21:10 ./src/main/java/henry416
drwxr-xr-x 2 henry henry 4096 2014-03-06 21:10 ./src/main/java/henry416/domain
-rw-r--r-- 1 henry henry  928 2014-03-06 21:10 ./src/main/java/henry416/domain/Department.java
-rw-r--r-- 1 henry henry  992 2014-03-06 21:10 ./src/main/java/henry416/domain/Employee.java
drwxr-xr-x 2 henry henry 4096 2014-03-06 21:10 ./src/main/java/henry416/jpa
-rw-r--r-- 1 henry henry 1597 2014-03-06 21:10 ./src/main/java/henry416/jpa/JpaTest.java
drwxr-xr-x 3 henry henry 4096 2014-03-06 21:10 ./src/main/resources
drwxr-xr-x 2 henry henry 4096 2014-03-06 21:10 ./src/main/resources/META-INF
-rw-r--r-- 1 henry henry 1205 2014-03-06 21:10 ./src/main/resources/META-INF/persistence.xml

The source codes you may be interested in the following separate links:
./pom.xml
./src/main/resources/META-INF/persistence.xml
./src/main/java/henry416/domain/Department.java
./src/main/java/henry416/domain/Employee.java
./src/main/java/henry416/jpa/JpaTest.java

3. Test Run

henry@brimley:~/Test/jpatest/test1$ cat run.sh
mvn compile exec:java -Dexec.mainClass=henry416.jpa.JpaTest

henry@brimley:~/Test/jpatest/test1$ chmod 700 *.sh

henry@brimley:~/Test/jpatest/test1$ ./run.sh 
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building test1 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test1 ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ test1 ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 3 source files to /home/henry/Test/jpatest/test1/target/classes
[INFO] 
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) @ test1 >>>
[INFO] 
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) @ test1 <<<
[INFO] 
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ test1 ---
num of employess:2
next employee: Employee [id=3, name=Captain Nemo, department=java]
next employee: Employee [id=2, name=Jakab Gipsz, department=java]
.. done
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 27.590s
[INFO] Finished at: Thu Mar 06 21:15:27 EST 2014
[INFO] Final Memory: 24M/61M
[INFO] ------------------------------------------------------------------------

4. Result

henry@brimley:~/Test/jpatest/test1$ cat show-derby.sh 
mvn dependency:copy-dependencies
java -cp 'target/dependency/*' org.apache.derby.tools.ij -p ij.properties

henry@brimley:~/Test/jpatest/test1$ ./show-derby.sh 
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building test1 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.8:copy-dependencies (default-cli) @ test1 ---
[INFO] Copying eclipselink-2.2.1.jar to /home/henry/Test/jpatest/test1/target/dependency/eclipselink-2.2.1.jar
[INFO] Copying derbytools-10.8.2.2.jar to /home/henry/Test/jpatest/test1/target/dependency/derbytools-10.8.2.2.jar
[INFO] Copying derby-10.8.2.2.jar to /home/henry/Test/jpatest/test1/target/dependency/derby-10.8.2.2.jar
[INFO] Copying javax.persistence-2.0.3.jar to /home/henry/Test/jpatest/test1/target/dependency/javax.persistence-2.0.3.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.026s
[INFO] Finished at: Thu Mar 06 21:17:51 EST 2014
[INFO] Final Memory: 8M/21M
[INFO] ------------------------------------------------------------------------
ij version 10.8
CONNECTION0* - 	jdbc:derby:simpleDb
* = current connection
ij> show schemas;
TABLE_SCHEM                   
------------------------------
APP                           
NULLID                        
SQLJ                          
SYS                           
SYSCAT                        
SYSCS_DIAG                    
SYSCS_UTIL                    
SYSFUN                        
SYSIBM                        
SYSPROC                       
SYSSTAT                       
TEST1                         

12 rows selected
ij> select * from TEST1.DEPARTMENT;
ID                  |NAME                
-----------------------------------------
1                   |java                

1 row selected
ij> select * from TEST1.EMPLOYEE;
ID                  |NAME                |DEPARTMENT_ID       
--------------------------------------------------------------
3                   |Captain Nemo        |1                   
2                   |Jakab Gipsz         |1                   

2 rows selected
ij> exit;

5. Deployment Target

henry@brimley:~/Test/jpatest/test1/target$ ls -ld $(find .)
drwxr-xr-x 4 henry henry    4096 2014-03-06 21:17 .
drwxr-xr-x 4 henry henry    4096 2014-03-06 21:15 ./classes
drwxr-xr-x 4 henry henry    4096 2014-03-06 21:15 ./classes/henry416
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:15 ./classes/henry416/domain
-rw-r--r-- 1 henry henry    1691 2014-03-06 21:15 ./classes/henry416/domain/Department.class
-rw-r--r-- 1 henry henry    1888 2014-03-06 21:15 ./classes/henry416/domain/Employee.class
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:15 ./classes/henry416/jpa
-rw-r--r-- 1 henry henry    3080 2014-03-06 21:15 ./classes/henry416/jpa/JpaTest.class
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:15 ./classes/META-INF
-rw-r--r-- 1 henry henry    1205 2014-03-06 21:15 ./classes/META-INF/persistence.xml
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:17 ./dependency
-rw-r--r-- 1 henry henry 2671577 2014-03-06 21:17 ./dependency/derby-10.8.2.2.jar
-rw-r--r-- 1 henry henry  174969 2014-03-06 21:17 ./dependency/derbytools-10.8.2.2.jar
-rw-r--r-- 1 henry henry 6412045 2014-03-06 21:17 ./dependency/eclipselink-2.2.1.jar
-rw-r--r-- 1 henry henry  126856 2014-03-06 21:17 ./dependency/javax.persistence-2.0.3.jar

6. Run As Java Application

henry@brimley:~/Test/jpatest/test1$ cd target/classes
henry@brimley:~/Test/jpatest/test1/target/classes$ java -cp '../dependency/*' henry416.jpa.JpaTest
num of employess:2
next employee: Employee [id=3, name=Captain Nemo, department=java]
next employee: Employee [id=2, name=Jakab Gipsz, department=java]
.. done

7. Summary

By using maven, it’s pretty easy to create a project structure for a JPA application (Kudos to you Lajos Papp). By replacing those POJO entity classes with your own classes, modifying persistence.xml to your local database and pom.xml to the latest maven repository, you can code a real world java application in JPA. I hope this will make JPA programming more interesting.

Undocumented SQL Server 2012 Express LocalDB

As a developer of Microsoft Visual Studio, SQL Server 2012 Express LocalDB probably has gotten onto your machine without your notice. I will document some of my exploration on LocalDB in this post.

Installation and Location

There are three ways to get LocalDB onto your machines:

  1. Install together when installing Microsoft Visual Studio 2013 (this is my case);
  2. Install by using SqlLocalDB.msi found in SQL Server 2012 Express
  3. Install by downloading from Microsoft Download Centre directly (here).

The installation location is default to C:\Program Files\Microsoft SQL Server\110\LocalDB\Binn where sqlserv.exe is the main application.

The tools (utilities) to operate the LocalDB are SqlLocalDB, SQLCMD and bcp which are located at C:\Program Files\Microsoft SQL Server\110\Tools\Binn. Make sure to include it into your PATH.

SqlLocalDB

This is the utility to administrate the localdb instances.

  • to get help: sqllocaldb -?
  • to print the version: sqllocaldb versions
  • to create an instance: sqllocaldb create “YourInstanceName”
  • to delete an instance: sqllocaldb delete “YourInstanceName”
  • to start an instance: sqllocaldb start “YourInstanceName”
  • to stop an instance: sqllocaldb stop “YourInstanceName”
  • to share an instance: sqllocaldb share “YourInstanceName”
  • to unshared an instance: sqllocadbl unshare “YourInstanceName”
  • to list all your instances: sqllocaldb info
  • to list the status of an instance: sqllocaldb info “YourInstanceName”
  • to set the trace on and off: sqllocaldb trace on|off

If you’ve used VS 2013 to connect to LocalDB, VS 2013 would have created an instance for you (in my case is v11.0).

Even your instance is stopped, it will be auto-started when you try to connect to it first time either via VS 2013 or SQLCMD.

SQLCMD, BCP, process ‘sqlservr’

Both SQLCMD and BCP are well documented. The only difference between LocalDB and SQL server is that we need to put a bracket ‘()’ to indicate it is a LocalDB instead of hostname for the named instance like:

sqlcmd -S ‘(LocalDB)\v11.0’

This is also applied to SSMS and VS 2013 connections. There is only one process “sqlservr” related to LocalDB. It is very lightweighted by using about 12MB RAM on my machine.

Some Examples

The following is executed in powershell:

Windows PowerShell
Copyright (C) 2013 Microsoft Corporation. All rights reserved.

PS C:\Users\henry> sqllocaldb info
Projects
v11.0
PS C:\Users\henry> sqllocaldb info "v11.0"
Name:               v11.0
Version:            11.0.3000.0
Shared name:
Owner:              PolarBear\henry
Auto-create:        Yes
State:              Stopped
Last start time:    12/31/2013 2:37:39 PM
Instance pipe name:
PS C:\Users\henry> sqllocaldb start "v11.0"
LocalDB instance "v11.0" started.
PS C:\Users\henry>  ps | where-object {$_.ProcessName -match 'sqlservr'}

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    492      20    67780      17140   311     3.83   2248 sqlservr


PS C:\Users\henry> sqllocaldb stop "v11.0"
LocalDB instance "v11.0" stopped.
PS C:\Users\henry> sqlcmd -S "(LocalDB)\v11.0"
1> use test
2> go
Changed database context to 'test'.
1> select count(*) from HR.Employees
2> go

-----------
          9

(1 rows affected)
1> shutdown
2> go
Server shut down by request from login PolarBear\henry.
1> exit
PS C:\Users\henry>

Sharing or Not

From A TechNet Article
When sharing a SqlLocalDB instance with a non-owner, you must re-start the instance for the other users to be able to see the instance you have shared. A non-owner cannot start an instance, so if you are going to share an instance with other users who can access your machine, you also need to be sure it has been started. When you create an instance you can do this as follows:

sqllocaldb create “MyInstance”
sqllocaldb share “MyInstance” “OurInstance”
sqllocaldb start “MyInstance”

You should add users explicitly when connected to the instance as the owner, e.g.

CREATE LOGIN [Domain\User] FROM WINDOWS;
GRANT CONNECT TO [Domain\User];
— other permissions…

In general, though, the purpose of SqlLocalDB is to serve as a sandbox for an individual developer on a machine, not to serve as a development environment for multiple users. Each user should be able to create, start, administer and use his/her own LocalDB instances.

Using Entity Framework in an ASP.NET MVC5 Application

In my previous two posts, I built a C# console application using Entity Framework (EF) in Microsoft Visual Studio 2013, and investigated how to perform CRUD operations on EF.

Building an ASP.NET MVC5 application using EF can become a straightforward job in Visual Studio 2013. It is very similar to building a J2EE MVC application by using JPA in Netbeans 7. The steps can be summarized as three steps: 1) create a ASP.NET MVC project; 2) add M: reversed engineer an EF model(M) from database; 3) Add C with V: scaffolding MVC 5 Controller (C) with views (V) using EF.

1. Create a ASP.NET MVC Project

In Microsoft Visual Studio 2013, create a new project (Ctrl-Shift-N) called EmployeeMVC using template (Visual C#->ASP.NET Web Application) and also select a template ‘MVC‘ and add folders and core references for ‘MVC’.

What will happene?
Visual Studio will create a few folders (App_Data, App_Start, Content, Controllers, fonts, Models, Scripts, Views) and files (Global.asax, packages.config, Web.config, Project_Readme.html, Startup.cs), also download a list of js scripts in Scripts folder, create AccountViewModels.cs and IdentityModels.cs in Models folder, AccountController.cs and HomeController.cs in Controllers folder, a list of *.shtml in various view folders, site style sheets in Contents folder and a few config.cs in App_Start.

Press F5 to build and run the empty application now.

2. Add ADO.NET Entity Data Model

Following the steps to reversed engineer EF 5 model from a table in the database into ASP.NET MVC (for reversed engineer an EF 6 model class, please use Entity Framework Power Tools):

  • Right click on Models folder, and choose New Item-Add->Data->ADO.NET Entity Data Model (C#);
  • Provide a Name: EmployeeModel.edmx and Click ‘Add’;
  • Choose ‘generate from database’ and Click ‘Next’
  • Connect to a SQL instance (local), choose your database (test) and table (HR.Employee)
  • If you receive a security warning, select OK to continue running the template.
  • This will add EmployeeModel.edmx (EF 5) as a folder under Models, and also add relevant references.

    Build the solution.

    3. Generate Controller and Views

    To generate controller and views:

  • Add the new controller to the existing Controllers folder. Right-click the Controllers folder, and select Add – New Scaffolded Item; Select the MVC 5 Controller with views, using Entity Framework option. This option will generate the controller and views for updating, deleting, creating and displaying the data in your model.
  • Set the controller name to EmployeeController, select Employee (EmployeeMVC.Models) for the model class, and select the testEntities (EmployeeMVC.Models) for the context class, Click ‘Add’
  • This will create EmployeeController.cs in Controllers:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using EmployeeMVC.Models;
    
    namespace EmployeeMVC.Controllers
    {
        public class EmployeeController : Controller
        {
            private testEntities db = new testEntities();
    
            // GET: /Employee/
            public ActionResult Index()
            {
                var employees = db.Employees.Include(e => e.Employee1);
                return View(employees.ToList());
            }
    
            // GET: /Employee/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }
                return View(employee);
            }
    
            // GET: /Employee/Create
            public ActionResult Create()
            {
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname");
                return View();
            }
    
            // POST: /Employee/Create
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include="empid,lastname,firstname,title,titleofcourtesy,birthdate,hiredate,address,city,region,postalcode,country,phone,mgrid")] Employee employee)
            {
                if (ModelState.IsValid)
                {
                    db.Employees.Add(employee);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname", employee.mgrid);
                return View(employee);
            }
    
            // GET: /Employee/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname", employee.mgrid);
                return View(employee);
            }
    
            // POST: /Employee/Edit/5
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include="empid,lastname,firstname,title,titleofcourtesy,birthdate,hiredate,address,city,region,postalcode,country,phone,mgrid")] Employee employee)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(employee).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.mgrid = new SelectList(db.Employees, "empid", "lastname", employee.mgrid);
                return View(employee);
            }
    
            // GET: /Employee/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee employee = db.Employees.Find(id);
                if (employee == null)
                {
                    return HttpNotFound();
                }
                return View(employee);
            }
    
            // POST: /Employee/Delete/5
            [HttpPost, ActionName("Delete")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteConfirmed(int id)
            {
                Employee employee = db.Employees.Find(id);
                db.Employees.Remove(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
        }
    }
    
    

    It will also create a folder ‘Employee‘ in Views with a list of cshtml (Create, Delete, Details, Edit, Index)

    Build and run by pressing F5, and go to the similar link in the browser like:
    http://localhost:49481/employee

    I removed some of unwanted items in index.cshtml. My index page looked like:

    ASP.NET MVC 5 using EF

    ASP.NET MVC 5 using EF

    Summary

    Using Entity Framework, Visual Studio 2013 can easily generate a model from database, and scaffold a controller and generate all the views based on default templates and standard CRUD operations on EF.

    The advantage of this process is that the model, controller and view can be easily re-generated by repeating the above step 2 and 3 if the table structure in the underlying physical table is changed.

    The disadvantage is also obvious. Whatever customization made after the generation on (M. V. C) will have to be repeated after re-generation.

    Using JPA to build a J2EE 3-tier Web Application

    The purpose of this entry is to demonstrate a full J2EE web application. The application will generate:

      1. a Java Persistence API (JPA) entity modeled on an existing database table
      2. an Enterprise JavaBean (EJB) which will query the database through the JPA
      3. a Servlet coupled with a JavaServer Faces (JSF) 2 framework for information display
      4. a Representational State Transfer (REST) resource capable of providing the JPA entities as web resources

    The project will be built in Netbeans 7.2.1 and hosted on Glassfish 3.2.1

    Start off by creating a Web Application project and specify the Glassfish Server. Then, clicking on the project, create a new Entity Class from Database (under Persistence) and specify the datasource along with the required tables. Specify a package. Check the NamedQuery, JAXB and Persistence Unit boxes.

    Image

    Next, create a new stateless EJB in the package (with the annotation @Stateless). We will be using JPA entities as RESTful resources, so tell netbeans to register all REST resources to the javax.ws.rs.Application class automatically and add a Jersey Library (JAX-RS implementation).

    @javax.inject.Named
    @Path("/customers")
    @Stateless
    public class CustomerSessionBean {
    
        @PersistenceContext
        EntityManager em;
    
        public List<Customer> getCustomers() {
            return (List<Customer>)em.createNamedQuery("Customer.findAll").getResultList();
        }
    
        //RESTful resource, access at http://localhost:8080/JavaEE6SampleApp/webresources/customers/customer/1
        @GET
        @Path("/customer/{id}")
        @Produces("application/xml")
        public Customer getCustomer(@PathParam("id")Integer id) {
            return
            (Customer)em.createNamedQuery("Customer.findByCustomerId")
            .setParameter("customerId", id).getSingleResult();
        }
    }
    

    Next, create the servlet that uses the EJB.

    @WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
    public class TestServlet extends HttpServlet {
    
        @EJB CustomerSessionBean ejb;
    
        // Access at http://localhost:8080/JavaEE6SampleApp/TestServlet
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet TestServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet TestServlet at " + request.getContextPath () + "</h1>");
                out.println(ejb.getCustomers());
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        }
    
        // HTTPServlet Methods go here
    }
    

    Next, we will go about creating the Context and Dependency Injection (CDI) which allows the EJB to support the JSF pages. Create a beans.xml file in the project and set the project framework to JSF. Create a Facelets Template (JSF) in the WEB-INF folder using one of the CSS layouts. Edit it to become:

    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:ui="http://java.sun.com/jsf/facelets"
          xmlns:h="http://java.sun.com/jsf/html">
        <h:head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link href="./../resources/css/default.css" rel="stylesheet" type="text/css" />
            <link href="./../resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
            <title>Facelets Template</title>
        </h:head>
        <h:body>
            <div id="top">
                <ui:insert name="top"><h1>Java EE 6 Sample App</h1></ui:insert>
            </div>
    
            <div id="content" class="center_content">
                <ui:insert name="content">Content</ui:insert>
            </div>
    
            <div id="bottom">
                <ui:insert name="bottom"><center>DEMO!</center></ui:insert>
            </div>
        </h:body>
    </html>
    

    Delete the old index.xhtml file and replace it with a new Facelets Template Client copy. In this case, the root tag used is :

    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
                    template="./WEB-INF/template.xhtml"
                    xmlns:h="http://java.sun.com/jsf/html">
        <ui:define name="content">
            <h:dataTable value="#{customerSessionBean.customers}" var="c">
                <h:column>#{c.name}</h:column>
                <h:column>#{c.customerId}</h:column>
            </h:dataTable>
        </ui:define>
    </ui:composition>
    

    And we are done. The final results are:

    Screenshot from 2013-01-07 12:34:30 Screenshot from 2013-01-07 12:34:43 Screenshot from 2013-01-07 12:34:53 Screenshot from 2013-01-07 12:35:17

    Some tricks on Visual Studio 2010

    •Suggestion mode [CTRL]+[ALT]+[SPACE]
    •Find all references [SHIFT]+[F12]
    •Navigating Highlights   [CTRL]+[SHIFT]+[UP|DOWN]
    •Code: ZOOM Mouse and Keyboard   [CTRL]+[SHIFT]+[<|>]
    •Outline Hide [CTRL]+[M],[H]
    •Outline Show [CTRL]+[M],[U]
    •Smart Tag Shortcut [CTRL]+[.]
    Code Snippets
    •Double [TAB] Expansion
    •Insert Snippet

    [CTRL]+[K] and [CTRL]+[X]