The
VinylHandler Servlet allows a user to add a Vinyl to the collection and lists their current collection in a tabular format. A Vinyl record contains: 1. Title
2. Artist
3. Genre
4. Year
5. Playing Time
When a new Vinyl is submitted via the JSP page, the Servlet creates a corresponding Vinyl object, which is added to the session and a java.util.List object contains all Vinyls in the session. Accordingly, the table of existing Vinyls are then built by retrieving all Vinyl objects from the session and generating HTML for each Vinyl, while following the MVC (“Model 2”) architecture. Additionally, allowing all individual Vinyls to be deleted and modified from the list. The modification UI is provided using a separate JSP page.
Next, a new “generate report” feature was added, which provides a read-only printer-friendly view of the Vinyls currently in the collection. The generate report button is on the same page as the one allowing the user to add a Vinyl. The Servlet generates and returns an XML file in the HttpServletResponse, following the correct media (MIME) type. The XML also contains a processing instruction so that the browser will apply the xslt stylesheet Vinyls.xsl.
Next, an option to sort lists by genre, artist, year, or none (order added) was added, before generating a report. The JSP page defines a new page for editing a single Vinyl and uses the bean tag syntax to access the active Vinyl object from the session. It then sets the values of appropriate form controls according to the current values of the Vinyl, again, using bean tag syntax. An update button is provided that submits the form back to the controller Servlet.
Finally, the list of Vinyls are stored in the database where the application acquires a DataSource via JNDI in the Servlet.
*/
@SuppressWarnings("unchecked")
public class VinylHandler extends HttpServlet {
// -----------------------------------------------------------------------------
private DataSource dataSource;
// -----------------------------------------------------------------------------
/**
* Initializes VinylHandler, loads the database driver and establishes a connection.
* @param conf servlet configuration
* @Override
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
dataSource = (DataSource)envCtx.lookup("jdbc/MyCDDB");
} catch (NamingException e) {e.printStackTrace();}
} // End init().
// -----------------------------------------------------------------------------
/**
* Grabs a connection from the pool.
* @return dataSource A connection to the database.
* @throws SQLException
*/
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
// -----------------------------------------------------------------------------
/**
* Processes requests for both HTTP
GET and POST methods.* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection connection = null; Statement statement = null;
HttpSession session = request.getSession();
if(session == null){response.sendRedirect("error.html");}
ArrayList
if (vinylList == null) {
vinylList = new ArrayList
session.setAttribute("vintlList", vinylList);
} // End if.
// An XML serializer.
LSSerializer writer = null;
// The DOM document.
Document document = null;
// Instantiate a vinyl object.
Vinyl record = null;
// Query.
String query = null;
// ID.
Integer vinylID = null;
System.out.println("--------------------------------------------------------I am here!!!!!!!!!!!!!!!!!!!!!");
// Retrieve the action parameter.
String action = request.getParameter("action");
// -----------------------------------------------------------------------------
if (action.equals("LOGIN")) {
// Retrieve the username.
String username = request.getParameter("username");
System.out.println("--------------------------------------------------------Test: The username is " + username);
// Place a reference to this user in the session.
session.setAttribute("username", username);
// Retrieve remaining login info.
String password = request.getParameter("password");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
try{
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Enter user into the database.
/* NOTE: No check is performed to see if the user currently exists or
whether the info was entered correctly */
query = "INSERT INTO Flewwelling_UserTable VALUES ('" + username + "', '"
+ password + "', '"
+ firstname + "', '"
+ lastname + "')";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// ADD vinyl to the collection.
} else if (action.equals("ADD")) {
// Increment the vinyl id.
vinylID = (Integer)session.getAttribute("vinylID");
// Determine if new session.
if(vinylID != null){
// Increment the vinylID.
vinylID++;
// Store the vinyl id for this session.
session.setAttribute("vinylID", vinylID);
}
// Retrieve the record.
record = getVinyl(request);
// Add first record to the list.
vinylList.add(record);
// Retrieve the new vinylID.
vinylID = (Integer)record.getID();
// Store the vinyl id for this session.
session.setAttribute("vinylID", vinylID);
System.out.println("----------------------------------------------------Test: The vinylID for ADD is " + vinylID);
try{
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Retrieve the username.
String user = (String)session.getAttribute("username");
// Insert record into the database.
query = "INSERT INTO Flewwelling_VinylTable VALUES ('" + user + "', '"
+ record.getID() + "', '"
+ record.getTitle() + "', '"
+ record.getArtist() + "', '"
+ record.getGenre() + "', '"
+ record.getYear() + "', '"
+ record.getDuration() + "')";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// Delete vinyl from the collection.
} else if (action.equals("DELETE")) {
// Retrieve the delete index param.
String delete = request.getParameter("delindex");
// Convert to an integer used as an index to access the record in the list.
int d = (new Integer(delete)).intValue();
//Retrieve the record before deletion.
record = vinylList.get(d);
// Remove Vinyl.
vinylList.remove(d);
try {
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Retrieve the username for the session.
String user = (String)session.getAttribute("username");
// Delete the specified record from the database.
query = "DELETE FROM Flewwelling_VinylTable WHERE UserID = '" + user + "' and VinylID = '"
+ record.getID() + "'and Title = '"
+ record.getTitle() + "' and Artist = '"
+ record.getArtist() + "' and Genre = '"
+ record.getGenre() + "' and Year = '"
+ record.getYear() + "' and Duration = '"
+ record.getDuration() + "'";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// Modify vinyl entry.
} else if (action.equals("EDIT")) {
// Retrieve edit index param.
String edit = request.getParameter("editindex");
// Convert to an integer used as an index to access the record in the list.
int index = (new Integer(edit)).intValue();
// Retrieve the specified record.
record = vinylList.get(index);
// Place a reference to this Vinyl object in the session.
session.setAttribute("record", record);
// Forward request to Modify.jsp.
String url = "/Modify.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);
return;
// -----------------------------------------------------------------------------
// Update the vinyl in the collection.
} else if (action.equals("UPDATE")) {
// Retrieve modify index param.
String update = request.getParameter("modindex");
// Convert to an integer used as an index to access the record in the list.
int pointer = (new Integer(update)).intValue();
// Retrieve the vinyl id.
//vinylID = (Integer)request.getSession().getAttribute("vinylID");
System.out.println("----------------------------------------------------Test: The vinylID for UPDATE is " + vinylID);
// Retrieve the modified record.
record = getVinyl(request);
System.out.println("----------------------------------------------------Updated record: " +record.getTitle()+" "+record.getArtist()+" "+record.getGenre()+" "+record.getYear()+" "+record.getDuration());
// Replace the modified record with the exisiting one.
vinylList.set(pointer, record);
// Retrieve the old record.
Vinyl oldRecord = (Vinyl)session.getAttribute("record");
System.out.println("----------------------------------------------------Unmodified record: " +oldRecord.getTitle()+" "+oldRecord.getArtist()+" "+oldRecord.getGenre()+" "+oldRecord.getYear()+" "+oldRecord.getDuration());
try {
// Establish a connection to the database.
connection = getConnection();
// Create a statement for executing queries.
statement = connection.createStatement();
// Retrieve the username.
String user = (String)session.getAttribute("username");
// Modify the specified record.
query = "UPDATE Flewwelling_VinylTable SET UserID = '" + user + "', VinylID = '"
+ oldRecord.getID() + "', Title = '"
+ record.getTitle() + "', Artist = '"
+ record.getArtist() + "', Genre = '"
+ record.getGenre() + "', Year = '"
+ record.getYear() + "', Duration = '"
+ record.getDuration() + "' WHERE UserID = '"
+ user + "' and VinylID = '"
+ oldRecord.getID() + "' and Title = '"
+ oldRecord.getTitle() + "' and Artist = '"
+ oldRecord.getArtist() + "' and Genre = '"
+ oldRecord.getGenre() + "' and Year = '"
+ oldRecord.getYear() + "' and Duration = '"
+ oldRecord.getDuration() + "'";
statement.executeUpdate(query);
// Close connection.
connection.close();
} catch(SQLException sqle) {System.err.println("Error with connection: " + sqle);
} finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
// -----------------------------------------------------------------------------
// Generate the collection.
} else if (action.equals("GENERATE")) {
try {
// Get an instance of the DOMImplementation registry.
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
// Get a DOM level 3 implementation.
DOMImplementation domImplementation = registry.getDOMImplementation("XML 3.0");
if (domImplementation == null) { // can't proceed -- config error
throw new RuntimeException ("No DOM 3.0 implementation found in classpath");
}
// Get an XML serializer.
if (domImplementation.hasFeature ("LS", "3.0")) {
writer = ((DOMImplementationLS) domImplementation.getFeature ("LS", "3.0")).createLSSerializer ();
} else { // can't proceed -- config error
throw new RuntimeException ("DOM implementation does not support serialization");
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
domImplementation = db.getDOMImplementation();
String qualifiedName = "cdlist";
String publicId = "-//j2ee dalcte//cd list//EN";
String systemId = "CDList.dtd";
// Create the DocumentType using DOMImplementation.createDocumentType.
DocumentType documentType = domImplementation.createDocumentType(qualifiedName, publicId, systemId);
// Create the Document, passing the DocumentType object to the DOMImplementation.createDocument method.
document = domImplementation.createDocument(null, documentType.getName(), null);
} catch (ClassNotFoundException ce) {
throw new RuntimeException (ce);
} catch (InstantiationException ie) {
throw new RuntimeException (ie);
} catch (IllegalAccessException ie) {
throw new RuntimeException (ie);
}catch(ParserConfigurationException pce) {System.out.println("Error while trying to instantiate DocumentBuilder " + pce);}
// Perform processing instruction.
ProcessingInstruction myPI = document.createProcessingInstruction("xml-stylesheet","type=\"text/xml\" href=\"CDs.xsl\"");
// Create root element - cdList.
Element cdlist = document.getDocumentElement();
// Insert before.
document.insertBefore(myPI, cdlist);
// -----------------------------------------------------------------------------
// Determine the desired sorting order and insert the order as an attribute in the root element.
String sortorder = request.getParameter("sortorder");
if(sortorder != null){
if(sortorder.equals("artist"))
{
System.out.println("----------sortby artist----------");
}
else if (sortorder.equals("genre")){System.out.println("----------sortby genre----------");}
else if (sortorder.equals("year")){System.out.println("----------sortby year----------");}
else {System.out.println("----------sortby order added----------");}
}
else{System.out.println("----------Note: No sorting order!----------");}
cdlist.setAttribute("sortorder", sortorder);
// -----------------------------------------------------------------------------
// Instantiate an iterator which points to the vinyl list.
Iterator it = vinylList.iterator();
while(it.hasNext()){
Vinyl cdz = (Vinyl)it.next();
Element cdElement = createCDElement(document, cdz);
cdlist.appendChild(cdElement);
} // End while.
// Set content type.
response.setContentType("text/xml");
// Serialize document to a String.
String str = writer.writeToString(document);
OutputStream out = response.getOutputStream () ;
PrintWriter pw = new PrintWriter(out);
pw.print(str);
pw.flush();
return;
} // End GENERATE.
// -----------------------------------------------------------------------------
String url = "/VinylInterface.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);
} // End processRequest().
/**
* Returns a Vinyl object.
* @param request Servlet request.
* @param id The id of the specified record.
* @return record A Vinyl object.
*/
private Vinyl getVinyl(HttpServletRequest request) {
Integer index = 0;
Integer vinylID = (Integer)request.getSession().getAttribute("vinylID");
System.out.println("--------------------------------------------------------The id for getVinyl() " + vinylID);
if (vinylID == null){
// Retrieve the username for this session.
String s = (String)request.getSession().getAttribute("username");
System.out.println("----------------------------------------------------The username for this session is " + s);
// Call getTableIndex() to retrieve the index and determine if user already exists in the database.
index = getTableIndex(s);
// Increment the index.
index++;
} else { index = vinylID; }
// Create a new Vinyl Instance.
Vinyl record = new Vinyl(index,
request.getParameter("title"),
request.getParameter("artist"),
request.getParameter("genre"),
request.getParameter("year"),
request.getParameter("duration"));
// Return the Vinyl.
return record;
} // End getVinyl().
/**
* Returns the max index in the list for the specified user.
* @param UserId The username of the specified user.
* @return result The greatest index(VinylID) in the list for the specified user.
*/
private Integer getTableIndex(String UserID){
Integer result = 0;
try {
// Establish a connection to the database.
Connection connection = getConnection();
// Create a statement for executing queries.
Statement statement = connection.createStatement();
// query.
String query = "SELECT VinylID FROM Flewwelling_VinylTable WHERE UserID = '" + UserID + "'";
ResultSet rs = statement.executeQuery(query);
if(rs.last()){
if(rs.getString("VinylID") == null){return new Integer(0);}
result = new Integer(rs.getString("VinylID"));
}
// Close connection.
connection.close();
} catch(SQLException e) {System.err.println("Unable to get max index: " + e.getMessage());
result = null;
}
return result;
}
/**
* Builds the DOMTREE and returns a Vinyl element.
* @param document The document.
* @param cdz A vinyl object.
* @return cd A Vinyl element.
*/
private Element createCDElement(Document document, Vinyl cdz){
Element cd = document.createElement("cd");
Element title = document.createElement("title");
title.appendChild(document.createTextNode(cdz.getTitle()));
cd.appendChild(title);
Element artist = document.createElement("artist");
artist.appendChild(document.createTextNode(cdz.getArtist()));
cd.appendChild(artist);
Element genre = document.createElement("genre");
genre.appendChild(document.createTextNode(cdz.getGenre()));
cd.appendChild(genre);
Element year = document.createElement("year");
year.appendChild(document.createTextNode(cdz.getYear()));
cd.appendChild(year);
Element duration = document.createElement("duration");
duration.appendChild(document.createTextNode(cdz.getDuration()));
cd.appendChild(duration);
return cd;
} //End createCDElement.
// -----------------------------------------------------------------------------
//
/**
* Handles the HTTP
GET method.* @param request servlet request
* @param response servlet response
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
POST method.* @param request servlet request
* @param response servlet response
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
@Override
public String getServletInfo() {
return "Short description";
}
//
} // End VinylHandler.
No comments:
Post a Comment