Upload
ngodien
View
223
Download
1
Embed Size (px)
Citation preview
1
Programming Assignment 1
Due February 20, 2013
Send your NetBeans project to (with Subject: A1-DS Firstname.Lastname)
Note: your NetBeans project(s) must be attached as a compressed ZIP folder in your email.
In this assignment, we plan to develop two simple web applications based on guestbookapp
database schema in MySQL server, JSP(EL/JSTL), Servlet, JPA (Java Persistence API), JTA
(Java Transaction API), and session EJB.
From this assignment, you will get useful hands-on experience for developing web applications
by NetBeans IDE, MySQL DBMS, and Java EE 6 technologies.
Data source and Connection Pool for database access need to be created by the JNDI/JDBC and
GrassFish database service configuration.
You will develop two projects:
o guestBookApp1 application is developed without creating guestbook1 database table.
Guestbook table will be created by the controller Servlet using JPA (with GuestBook1
entity class) and JTA
o guestBookApp2 application is developed from a database table guestbook2. From the
guestbook2 table, entity class and session EJB are created. Then you need to write
controller Servlet and JSP (follow Model View Controller design pattern (or
architecture))
Developing guestBookApp1 project
guestBookApp1 web application snap shot
Create New Project as shown below
2
Choose Java Web Category then select Web Application
3
Click Next and enter project name and select project folder location.
Click Next then click Finish
4
GuestBookApp1 project is created by the IDE as shown below. Explore the project structure by clicking
Projects, Files, and Services tabs as shown below.
Click Services tab and expand Databases. You need to register MySQL server in the NetBeans IDE.
Refer to the following Netbeans Ecommerce tutorial site to register MySQL server in the NetBeans IDE.
http://netbeans.org/kb/docs/javaee/ecommerce/setup-dev-environ.html
5
After MySQL server is registered, you will see MySQL Server icon as shown above.
Click Projects tab, and create a new folder as shown below.
6
Type folder name as controller and click finish
Right click controller, and add new file (i.e., select Web category and Servlet file, then click next)
7
Name the Servlet as GuestBookApp1Controller
Click Next
Click the check box “Add Information to deployment descriptor (web.xml)”. The web.xml deployment
descriptor file is optional (Servlet annotation can replace this from Servlet API 3.0). Click finish
Two files (GuestBookApp1Controller.java and web.xml) are created as shown below.
8
Create database (schema) guestbookapp as follows:
Then connect to the database guestbookapp in order to access the database by JNDI/JDBC DataSource.
9
Initially no database table is created. The gustbook1 database table will be created by the Servlet (using
JPA and JTA).
Create a new folder named entity in the Source Packages as shown below
Create a new Java Entity class by selecting Persistence category then selecting Entity class.
10
Click next, check Create Persistence Unit check box as shown below.
11
Select new Data Source and select gustbookapp Database Connection as shown below.
GuestBook1.java entity class will then be created.
@Entity
public class GuestBook1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
12
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof GuestBook1)) {
return false;
}
GuestBook1 other = (GuestBook1) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.GuestBook[ id=" + id + " ]";
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
13
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
You get syntax errors, fix the errors by clicking on red dot icons (e.g., an icon pointed to by the first
arrow) and by following suggestions from the IDE. For example, to fix the first syntax error, click “Add
import javax.persistence.Entity” suggestion. Repeat these steps for all red dot icons to import necessary
packages.
Double click on GuestBookApp1Controller.java, and then edit the Servlet as shown below.
@WebServlet(name = "GuestBookApp1Controller", urlPatterns = {"/GuestBookApp1Controller"})
public class GuestBookApp1Controller extends HttpServlet {
@PersistenceContext(unitName = "GuestBookApp1PU")
private EntityManager em;
14
@Resource
UserTransaction utx;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
utx.begin();
GuestBook1 g = new GuestBook1();
g.setFirstName(request.getParameter("firstname"));
g.setLastName(request.getParameter("lastname"));
em.persist(g);
List<GuestBook1> guestList = em.createQuery("select g from GuestBook1 g").getResultList();
request.setAttribute("guestList", guestList);
utx.commit();
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
try {
utx.rollback();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the
left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
15
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Fix syntax errors by importing necessary packages by using IDE code suggestions as explained above.
Double click index.jsp and edit the code as shown below.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : index
Created on : Feb 3, 2013, 2:44:52 PM
Author : gjung
16
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guest Book Based on Java Persistence API and Java Trasaction API</title>
</head>
<h1> Guest Users</h1>
<body>
<c:forEach var="guest" items="${guestList}">
<p>${guest.firstName} ${guest.lastName} </p>
</c:forEach>
<form method="post" action="GuestBook">
<h1>Sign On the Guest Book</h1>
<table>
<tr><td>First Name:</td><td><input type="text" name="firstname" /></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lastname" /></td></tr>
<tr><td>
<input type="submit" value="Sign on Guest Book"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Clean/Build, Deploy, Run the GuestBook1 project
17
Refresh guestbookapp database, and make sure gustbook1 database table is created. Then view data in the
table by Netbeans SQL editor as shown below (select * from guestbook1).
18
Developing guestBookApp2 project
Create a new data model using MySQL Workbench.
File/New Model
Create new schema as follows
19
Add guestbook2 table as shown below.
Then create SQL statement from the EER Diagram by Forward Engineer tool as shown below.
20
Copy the highlighted script to a file guestbook2.sql
Run the copied SQL statements by MySQL Workbench SQL Editor. Execute SQL statements by clicking
the icon pointed to by the red arrow as shown below.
21
Make sure guestbook2 table is created in guestbookapp database schema as shown below.
Now create new project GuestBookApp2.
22
Create Entity class from Database as shown below.
23
Choose guestbook2 then click Add
Then new entity class Guestbook2.java is created as shown below.
24
You then create a new stateless Session EJB for the entity class Guestbook2.java as shown below.
25
Examine your Guestbook2Facade.java session EJB created by the IDE and edit it based on the following
code snippet.
@Stateless
public class Guestbook2Facade extends AbstractFacade<Guestbook2> {
@PersistenceContext(unitName = "GuestBookApp2PU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
26
public Guestbook2Facade() {
super(Guestbook2.class);
}
public void persistGuestBookData(int id, String firstName, String lastName){
try {
Guestbook2 g = new Guestbook2();
g.setId(id);
g.setFirstname(firstName);
g.setLastname(lastName);
em.persist(g);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Write your Guestbook2Controller.java Servlet and edit it based on the following code snippet.
@WebServlet(name = "GuestBookApp2Controller", urlPatterns = {"/GuestBookApp2Controller"})
public class GuestBookApp2Controller extends HttpServlet {
@EJB
private Guestbook2Facade guestbook2SessionObj;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("guestID"));
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
guestbook2SessionObj.persistGuestBookData(id, firstName, lastName);
List<Guestbook2> guestList = guestbook2SessionObj.findAll();
request.setAttribute("guestList", guestList);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
Examine your index.jsp code and edit it based on the following code snippet.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
27
<%--
Document : index
Created on : Feb 3, 2013, 2:44:52 PM
Author : gjung
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guest Book Based on Java Persistence API and Java Trasaction API</title>
</head>
<h1> Guest Users</h1>
<body>
<c:forEach var="guest" items="${guestList}">
<p>${guest.id} ${guest.firstname} ${guest.lastname} </p>
</c:forEach>
<form method="post" action="GuestBookApp2Controller">
<h1>Sign On the Guest Book</h1>
<table>
<tr><td>ID:</td><td><input type="text" name="guestID" /></td></tr>
<tr><td>First Name:</td><td><input type="text" name="firstname" /></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lastname" /></td></tr>
<tr><td>
<input type="submit" value="Sign on Guest Book"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Clean/Build, Deploy, and Run the project
28
Make sure guestbook2 table is updated by the GuestBook2 project as shown below.