You are on page 1of 8

Web application with servlets and JPA

1. New Project

Server will need to be GlassFish, Tomcat-6 doesnt support JPAs resource


injection of EntityManagerFactory etc. (It didnt in 6.0.14; maybe things will
have changed by the time you read this.)
2. (No frameworks used, so skip through to finish)
3. NetBeans creates project with a dummy JSP; this not required; delete it.
Will need some Welcome Page in the project; create a simple HTML page (as
index.html), and then edit the web.xml file to reference this as welcome page
rather than the index.jsp file that has been removed.

4. Add a css stylesheet, defining some enhanced presentation formats for use by the
servlets etc.
5. In Source Packages, add a package mystuff
6. Add a servlet class, FormServlet. This first version of the servlet simply displays
a page with a list of string values fetched from the database via JPA. The servlet
has just a doGet method (so remove doPost and the auto-generated
processRequest function)

This servlet is going to have a lot of code generating HTML. This wouldnt be
desirable in a real application (JSPs would be preferable) but will suffice for this
simple demonstration.
It is going to have to get a list of the schools names; so it will have some JPA
code. It is going to need to use Entity classes School, Pupil, Teacher. (It only
uses School, but since School references Pupil and Teacher it will need all three.)
Will need to get definitions of classes generated from existing entries in database.
Before we can do that, we need to set up a Persistence Unit describing the
database.
7. Define a persistence unit and a database connection; dialogs

Oracle will usually be at port 1521. <HOST><PORT><SID> must all be


completed along with a user name and password.
(Disable the create table option in the persistence unit the tables already exist.)
The DataSource has to be defined in your AppServer with an appropriate
connection pool. If AppServer is running, NetBeans will invoke operations to
define a connection pool and JDBC JNDI name for the datasource. If there are
problems, you may have to define these yourself; making sure that the JNDI name
that you assign in AppServer/Admin matches the name used for the datasource in
NetBeans dialog.
8. Create Entity classes from the existing database tables.
Pick new entity class from database and in resulting dialog specify the
datasource that was just set up.
NetBeans should connect and retrieve metadata on the available tables and then
list these. If no tables are shown then either your datasource definition was
invalid, or you are using an out-of-date Oracle driver, or you have established a
connection to the database but have since been timed out, or you are getting too
many connections to the database.
The Entity classes generated will usually require some editing, if simply the
replacement of functions like toString() with application defined implementations
that produce some useful output.

NetBeans should add three classes to project with definitions of these entities, all
marked up with persistence annotations.

Edit the servlet.


(Remove the processRequest and doPost methods)
Add an instance data member of type EntityManagerFactory and annotate it with a
javax.persistence.PersistenceUnit tag (unitName attribute should match name of
persistence unit defined in persistence.xml file; apparently the unitName is optional,
JPA will find the persistence unit if there is only one defined.)
public class FormServlet extends HttpServlet {
@PersistenceUnit(unitName="WebSchoolDemo2PU")
private EntityManagerFactory emf;

NetBeans will not be able to resolve these datatypes! We must add the TopLink
libraries to the Libraries section of the project. We should also add the Oracle
drivers at the same time.

NetBeans Fix imports command should now be able to resolve


EntityManagerFactory etc.
Add a method that will use JPA to get a String[] with the names of all the schools
defined in the Schools table.

private String[] getSchoolNames() {


String[] results = null;
EntityManager em = null;

em = emf.createEntityManager();
Query q = em.createQuery(
"Select s.schoolname from School s");
List<String> names = q.getResultList();
em.close();
results = names.toArray(new String[0]);
return results;
}

(When fixing imports, make q a javax.persistence.Query!)


Complete a simple doGet() function that presents a HTML page that lists the school
names in a HTML ul style list.
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String[] names = getSchoolNames();
out.println(
"<html><head><title>JPA Demo</title>" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"./mystyle.css\">"
+
"</head>");
out.println("<body>");
out.println("<h1>Erehwon School Board</h1>");
out.println("<h2>Schools</h2>");
out.println("<ul>");
for(String name : names)
out.println("<li>" + name + "</li>");
out.println("</ul>");
out.println("</body></html>");

9. This limited application can then be deployed and run to check all connections to
databases etc. The code will be refined later.
Start AppServer (You may find it necessary to start the appserver separately rather
than use the menu in NetBeans servers-window; an attempt to start the server
from within NetBeans will sometimes cause the system to hang; on launch, it tries
to connect to Suns web site, if this fails it hangs.)
Build main project, select project in projects window, Undeploy and Deploy
Web-browser to localhost:8080/WebSchoolDemo2, thence to servlet

You might also like